The Python Oracle

How do I merge a list of dicts into a single dict?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5

--

Chapters
00:00 Question
00:39 Accepted answer (Score 278)
00:58 Answer 2 (Score 169)
01:20 Answer 3 (Score 17)
01:46 Answer 4 (Score 13)
02:23 Thank you

--

Full question
https://stackoverflow.com/questions/3494...

Question links:
[How to merge dicts, collecting values from matching keys?]: https://stackoverflow.com/questions/5946...

Accepted answer links:
[comprehension]: https://www.python.org/dev/peps/pep-0274/

Answer 2 links:
[ChainMap]: https://docs.python.org/3/library/collec...
[What is the purpose of collections.ChainMap?]: https://stackoverflow.com/questions/2339...

Answer 3 links:
[@dietbuddha]: https://stackoverflow.com/users/247357/d...
[PEP 448]: https://www.python.org/dev/peps/pep-0448/
[faster as well]: https://gist.github.com/treyhunner/f3529...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #dictionary

#avk47



ACCEPTED ANSWER

Score 319


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



ANSWER 2

Score 187


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:




ANSWER 3

Score 16


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




ANSWER 4

Score 12


For flat dictionaries you can do this:

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