Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中将字典列表转换为列表字典?_Python_Dictionary - Fatal编程技术网

如何在Python中将字典列表转换为列表字典?

如何在Python中将字典列表转换为列表字典?,python,dictionary,Python,Dictionary,这可能是Python中的一个经典问题,但我还没有找到答案 我有一个字典列表,这些字典有相似的键。 看起来是这样的: [{0: myech.MatchingResponse at 0x10d6f7fd0, 3: myech.MatchingResponse at 0x10d9886d0, 6: myech.MatchingResponse at 0x10d6f7d90, 9: myech.MatchingResponse at 0x10d988ad0}, {0: myec

这可能是Python中的一个经典问题,但我还没有找到答案

我有一个字典列表,这些字典有相似的键。 看起来是这样的:

 [{0: myech.MatchingResponse at 0x10d6f7fd0, 
   3: myech.MatchingResponse at 0x10d9886d0,
   6: myech.MatchingResponse at 0x10d6f7d90,
   9: myech.MatchingResponse at 0x10d988ad0},
  {0: myech.MatchingResponse at 0x10d6f7b10,
   3: myech.MatchingResponse at 0x10d6f7f90>}]
我想得到一个以[0,3,6,9]为键,以“myech.MatchingResponse”列表为值的新字典


当然,我可以使用一个简单的循环来实现这一点,但我想知道是否有更有效的解决方案

假设您的列表被分配给一个名为mylist的变量

import collections

result = collections.defaultdict(list)

for d in dictionaries:
    for k, v in d.items():
        result[k].append(v)
mydic = {}
for dic in mylist:
    for key, value in dic.items():
        if key in mydic:
            mydic[key].append(value)
        else:
            mydic[key] = [value]

通过听写理解也可以做到这一点。。。可以是一行,但为了清晰起见,我将其保留为两行。:)

结果:

{0: ['a', 'x'], 9: ['d'], 3: ['b', 'y'], 6: ['c']}

如果你有一个字典,每个字典中都有相同的键,你可以把它们转换成一个列表字典,如下面的例子(其中一些人会认为比其他答案更为pythic)。p>


使用
dict.setdefault
collections.defaultdict
代替此选项!:DAlso这将不起作用,因为遍历字典会遍历它的键,因此,对于键,dic中的值,
,将引发错误。将dic.items()中的键、值更改为
。编辑:我刚刚为你更改了它为什么用dic={}初始化字典是错误的?@lizzie我看不出有什么错误。不要称它为dict,否则您将隐藏内置dict类,并且您将无法访问它,因为您的变量已使用了该名称。这听起来很奇怪,一个隐藏其自身类型的变量:p这不是询问者的类型after@OttoAllmendinger啊。。我误解了这个问题。。。请看一看正确的解决方案:)我不确定性能,但现在它是一个有效的答案这是非常缓慢的!相反(从目录列表到目录列表)见:相关:
{0: ['a', 'x'], 9: ['d'], 3: ['b', 'y'], 6: ['c']}
d = []
d.append({'a':1,'b':2})
d.append({'a':4,'b':3}) 
print(d)                                                               
[{'a': 1, 'b': 2}, {'a': 4, 'b': 3}]

newdict = {}
for k,v in d[0].items():
    newdict[k] = [x[k] for x in d]

print(newdict)
{'a': [1, 4], 'b': [2, 3]}