简体   繁体   English

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

[英]How do I convert a list of dictionaries to a dictionary of lists in Python?

It may be a classical question in Python, but I haven't found the answer yet. 它可能是Python中的经典问题,但我还没有找到答案。

I have a list of dictionaries, these dictionaries have similar keys. 我有一个词典列表,这些词典有类似的键。 It looks like this: 它看起来像这样:

 [{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>}]

I would like to get a new dictionary with [0,3,6,9] as keys, and lists of " myech.MatchingResponse" as values. 我希望得到一个以[0,3,6,9]为键的新词典,并将“myech.MatchingResponse”列表作为值。

Of course I can do this using a simple loop but I was wondering if there is a more efficient solution. 当然,我可以使用一个简单的循环来做到这一点,但我想知道是否有更有效的解决方案。

import collections

result = collections.defaultdict(list)

for d in dictionaries:
    for k, v in d.items():
        result[k].append(v)

let's say your list is assigned to a variable called mylist. 假设您的列表被分配给一个名为mylist的变量。

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

It's possible to do this with dict comprehension as well ... could be one line, but I've kept it as two lines for clarity. 也可以用dict理解来做到这一点......可能是一行,但为了清晰起见,我把它保留为两行。 :) :)

from itertools import chain

all_keys = set(chain(*[x.keys() for x in dd]))
print {k : [d[k] for d in dd if k in d] for k in all_keys}

Results in: 结果是:

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

If you have a list of dictionaries with identical keys in each, you can convert these to a dictionary of lists as in the following example, (which some would consider more pythonic than some of the other answers). 如果你有一个字典列表,每个字典都有相同的键,你可以将它们转换为列表字典,如下例所示(有些人会考虑比其他答案更pythonic)。

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]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM