问题:如何将字典列表合并为一个字典?

我该如何列出这样的词典

[{'a':1}, {'b':2}, {'c':1}, {'d':2}]

变成这样的单个字典

{'a':1, 'b':2, 'c':1, 'd':2}

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}

回答 0

这适用于任何长度的字典:

>>> result = {}
>>> for d in L:
...    result.update(d)
... 
>>> result
{'a':1,'c':1,'b':2,'d':2}

作为一个理解

# 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())

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())

回答 1

对于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}

另请参阅:

In case of Python 3.3+, there is a ChainMap collection:

>>> 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:


回答 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())
>>> 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

if the dicts can have more than one key/value

>>> dict(j for i in L for j in i.items())

回答 3

对于平面词典,您可以执行以下操作:

from functools import reduce
reduce(lambda a, b: dict(a, **b), list_of_dicts)

For flat dictionaries you can do this:

from functools import reduce
reduce(lambda a, b: dict(a, **b), list_of_dicts)

回答 4

这类似于@delnan,但提供了修改k / v(键/值)项的选项,并且我认为它更具可读性:

new_dict = {k:v for list_item in list_of_dicts for (k,v) in list_item.items()}

例如,替换k / v元素,如下所示:

new_dict = {str(k).replace(" ","_"):v for list_item in list_of_dicts for (k,v) in list_item.items()}

将dict对象从列表中拉出后,从字典.items()生成器中解压缩k,v元组

This is similar to @delnan but offers the option to modify the k/v (key/value) items and I believe is more readable:

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:

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


回答 5

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。

dict1.update( dict2 )

This is asymmetrical because you need to choose what to do with duplicate keys; in this case, dict2 will overwrite dict1. Exchange them for the other way.

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 for loop. YMMV.


回答 6

您可以使用来自funcy库的join函数:

from funcy import join
join(list_of_dicts)

You can use join function from funcy library:

from funcy import join
join(list_of_dicts)

回答 7

PEP 448中压缩字典后,@ dietbuddha答案的改进很少,对我来说,这种方式更易读,而且速度更快

from functools import reduce
result_dict = reduce(lambda a, b: {**a, **b}, list_of_dicts)

但是请记住,这仅适用于Python 3.5+版本。

Little improvement for @dietbuddha answer with dictionary unpacking from PEP 448, for me, it`s more readable this way, also, it is faster as well:

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.


回答 8

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

注意,我在最后典中添加了第二个键/值对,以显示它可用于多个条目。此外,列表中较晚位置的字典中的键将覆盖较早版本中的字典相同的键。

>>> 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.


回答 9

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}

dic1 = {‘Maria’:12, ‘Paco’:22, ‘Jose’:23} dic2 = {‘Patricia’:25, ‘Marcos’:22 ‘Tomas’:36}

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}


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。