我该如何列出这样的词典
[{'a':1}, {'b':2}, {'c':1}, {'d':2}]
变成这样的单个字典
{'a':1, 'b':2, 'c':1, 'd':2}
我该如何列出这样的词典
[{'a':1}, {'b':2}, {'c':1}, {'d':2}]
变成这样的单个字典
{'a':1, 'b':2, 'c':1, 'd':2}
Answers:
对于Python 3.3+,有一个ChainMap集合:
>>> from collections import ChainMap
>>> a = [{'a':1},{'b':2},{'c':1},{'d':2}]
>>> dict(ChainMap(*a))
{'b': 2, 'c': 1, 'a': 1, 'd': 2}
另请参阅:
>>> L=[{'a': 1}, {'b': 2}, {'c': 1}, {'d': 2}]
>>> dict(i.items()[0] for i in L)
{'a': 1, 'c': 1, 'b': 2, 'd': 2}
注意:“ b”和“ c”的顺序与您的输出不匹配,因为字典是无序的
如果字典可以具有多个键/值
>>> dict(j for i in L for j in i.items())
dict1.update( dict2 )
这是不对称的,因为您需要选择对重复的密钥进行处理。在这种情况下,dict2将覆盖dict1。换另一种方式。
编辑:啊,对不起,没有看到。
可以在单个表达式中执行此操作:
>>> from itertools import chain
>>> dict( chain( *map( dict.items, theDicts ) ) )
{'a': 1, 'c': 1, 'b': 2, 'd': 2}
最后一点都不归功于我!
但是,我认为通过一个简单的for循环执行此操作可能更像Pythonic(显式>隐式,flat> nested)。YMMV。
dic1 = {'Maria':12,'Paco':22,'Jose':23} dic2 = {'Patricia':25,'Marcos':22'Tomas':36}
dic2 = dict(dic1.items()+ dic2.items())
这将是结果:
dic2 {'Jose':23,'Marcos':22,'Patricia':25,'Tomas':36,'Paco':22,'Maria':12}