The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle4

--

Chapters
00:00 How Do I Merge A List Of Dicts Into A Single Dict?
00:28 Accepted Answer Score 319
00:44 Answer 2 Score 12
00:55 Answer 3 Score 187
01:12 Answer 4 Score 16
01:37 Thank you

--

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

--

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)