【问题标题】:How do I convert a list of dictionaries to a dictionary of lists in Python?如何将字典列表转换为 Python 中的列表字典?
【发布时间】:2012-07-12 03:05:40
【问题描述】:

这可能是 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”列表作为值。

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

【问题讨论】:

标签: python dictionary


【解决方案1】:
import collections

result = collections.defaultdict(list)

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

【讨论】:

  • 这非常慢! span>
【解决方案2】:

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

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

【讨论】:

  • 使用 dict.setdefaultcollections.defaultdict 代替这个! :D
  • 这也行不通,因为遍历字典会遍历它的键,所以 for key, value in dic 会引发错误。更改为for key, value in dic.items()。编辑:我只是为你改变了它
  • 为什么用 dic = {} 初始化字典是错误的?
  • @lizzie 我看不出有什么问题。只是不要称它为 dict 或者您正在隐藏内置的 dict 类,并且您将无法访问它,因为您的变量已使用该名称。
  • 这听起来很奇怪,一个变量隐藏了它自己的类型:p
【解决方案3】:

也可以使用 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}

结果:

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

【讨论】:

  • 这不是提问者所追求的
  • @OttoAllmendinger 啊..我误解了这个问题......请看看更正的解决方案:)
  • 我不确定性能,但现在它是一个有效的答案
【解决方案4】:

如果您有一个字典列表,每个字典都有相同的键,您可以将它们转换为列表字典,如下例所示(有些人认为这比其他一些答案更 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]}

【讨论】:

  • If you have a lists of dictionaries with identical keys。在实际提出的问题中,这明确不是的情况。那么,这是对另一个问题的回答吗?我提出一个更简短的答案; 42也是另一个问题的答案。
猜你喜欢
  • 2015-07-23
  • 2019-02-10
  • 1970-01-01
  • 1970-01-01
  • 2017-04-23
  • 2021-10-13
  • 2014-07-28
  • 1970-01-01
相关资源
最近更新 更多