Python 如何将字典列表合并为一个字典?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3494906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I merge a list of dicts into a single dict?
提问by killown
How can I turn a list of dicts like this
我怎样才能打开这样的字典列表
[{'a':1}, {'b':2}, {'c':1}, {'d':2}]
Into a single dict like this
变成这样的单个字典
{'a':1, 'b':2, 'c':1, 'd':2}
采纳答案by John La Rooy
This works for dictionaries of any length:
这适用于任何长度的字典:
>>> result = {}
>>> for d in L:
... result.update(d)
...
>>> result
{'a':1,'c':1,'b':2,'d':2}
As a comprehension:
作为一种理解:
# Python >= 2.7
{k: v for d in L for k, v in d.items()}
# Python < 2.7
dict(pair for d in L for pair in d.items())
回答by Katriel
dict1.update( dict2 )
This is asymmetrical because you need to choose what to do with duplicate keys; in this case, dict2will overwrite dict1. Exchange them for the other way.
这是不对称的,因为您需要选择如何处理重复的密钥;在这种情况下,dict2将覆盖dict1. 用另一种方式交换它们。
EDIT: Ah, sorry, didn't see that.
编辑:啊,对不起,没有看到。
It is possible to do this in a single expression:
可以在单个表达式中执行此操作:
>>> from itertools import chain
>>> dict( chain( *map( dict.items, theDicts ) ) )
{'a': 1, 'c': 1, 'b': 2, 'd': 2}
No credit to me for this last!
这最后一点不归功于我!
However, I'd argue that it might be more Pythonic (explicit > implicit, flat > nested ) to do this with a simple forloop. YMMV.
但是,我认为用一个简单的for循环来做到这一点可能更像 Pythonic(显式 > 隐式、平面 > 嵌套)。天啊。
回答by John La Rooy
>>> 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}
Note: the order of 'b' and 'c' doesn't match your output because dicts are unordered
注意:'b' 和 'c' 的顺序与您的输出不匹配,因为 dicts 是无序的
if the dicts can have more than one key/value
如果字典可以有多个键/值
>>> dict(j for i in L for j in i.items())
回答by Dave Kirby
>>> dictlist = [{'a':1},{'b':2},{'c':1},{'d':2, 'e':3}]
>>> dict(kv for d in dictlist for kv in d.iteritems())
{'a': 1, 'c': 1, 'b': 2, 'e': 3, 'd': 2}
>>>
Note I added a second key/value pair to the last dictionary to show it works with multiple entries. Also keys from dicts later in the list will overwrite the same key from an earlier dict.
注意我在最后一个字典中添加了第二个键/值对,以显示它适用于多个条目。此外,列表中后面的 dicts 中的键将覆盖早期 dict 中的相同键。
回答by dietbuddha
For flat dictionaries you can do this:
对于平面词典,您可以这样做:
from functools import reduce
reduce(lambda a, b: dict(a, **b), list_of_dicts)
回答by Suor
回答by Max Herrera
dic1 = {'Maria':12, 'Paco':22, 'Jose':23} dic2 = {'Patricia':25, 'Marcos':22 'Tomas':36}
dic1 = {'玛丽亚':12,'帕科':22,'何塞':23} dic2 = {'帕特里夏':25,'马科斯':22 '托马斯':36}
dic2 = dict(dic1.items() + dic2.items())
dic2 = dict(dic1.items() + dic2.items())
and this will be the outcome:
这将是结果:
dic2 {'Jose': 23, 'Marcos': 22, 'Patricia': 25, 'Tomas': 36, 'Paco': 22, 'Maria': 12}
dic2 {'何塞':23,'马科斯':22,'帕特里夏':25,'托马斯':36,'帕科':22,'玛丽亚':12}
回答by alecxe
In case of Python 3.3+, there is a ChainMapcollection:
在 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}
Also see:
另见:
回答by Schalton
This is similar to @delnan but offers the option to modify the k/v (key/value) items and I believe is more readable:
这类似于@delnan,但提供了修改 k/v(键/值)项的选项,我相信它更具可读性:
new_dict = {k:v for list_item in list_of_dicts for (k,v) in list_item.items()}
for instance, replace k/v elems as follows:
例如,将 k/v elems 替换如下:
new_dict = {str(k).replace(" ","_"):v for list_item in list_of_dicts for (k,v) in list_item.items()}
unpacks the k,v tuple from the dictionary .items() generator after pulling the dict object out of the list
将 dict 对象从列表中拉出后,从字典 .items() 生成器中解压 k,v 元组
回答by Insomniac631
Little improvement for @dietbuddhaanswer with dictionary unpacking from PEP 448, for me, it`s more readable this way, also, it is faster as well:
@dietbuddha答案与PEP 448 中的字典解包几乎没有改进,对我来说,这种方式更具可读性,而且速度也更快:
from functools import reduce
result_dict = reduce(lambda a, b: {**a, **b}, list_of_dicts)
But keep in mind, this works only with Python 3.5+ versions.
但请记住,这仅适用于 Python 3.5+ 版本。

