我有一个称为多的嵌套列表:

[[14, 77766 ,[2, 2]],
 [15, 77766,  [1, 2]],
 [70, 88866, [1, 5]],
 [71, 88866,[2, 5]],
 [72, 88866, [5, 5]],
 [73, 88866, [4, 5]],
 [74, 88866, [3, 5]],
 [79, 99966, [1, 2]],
 [80, 99966, [2, 2]]]


我需要我的输出是:

{77766:  {14:2 ,15:1} , 88866: {70:1, 71:2, 72:5, 73:4, 74:3}, 99966: {79:1, 80:2}}


我编写了产生以下两个词典的代码。如何结合它们以实现所需的输出?

a = {77766: [14, 15], 88866: [70, 71, 72, 73, 74], 99966: [79, 80]}


b = {14: 2, 15: 1, 70: 1, 71: 2, 72: 5, 73: 4, 74: 3, 79: 1, 80: 2}

最佳答案

您可以在此处使用defaultdictmulti无需排序。

from collections import defaultdict
out=defaultdict(dict)
for v,k,vs in multi:
    out[k]={**out[k],**{v:vs[0]}}




输出量

defaultdict(dict,
            {77766: {14: 2, 15: 1},
             88866: {70: 1, 71: 2, 72: 5, 73: 4, 74: 3},
             99966: {79: 1, 80: 2}})


编辑:

排序内部字典。

out={k:dict(sorted(v.items(),key=lambda x:x[1])) for k,v in out.items()}


输出:

{77766: {15: 1, 14: 2},
 88866: {70: 1, 71: 2, 74: 3, 73: 4, 72: 5},
 99966: {79: 1, 80: 2}}

10-07 23:16