How to combine a list of dicts into one dict?

EDIT

I have:

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

the conclusion should be:

 {'a':1,'b':2,'c':1,'d':2} 
+48
python
Aug 16 '10 at 15:55
source share
8 answers

This works for dictionaries of any length:

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

And as an oneliner generator:

 dict(pair for d in L for pair in d.items()) 

In Python 2.7 and 3.x, this can and should be written as an understanding of dict (thanks, @katrielalex):

 { k: v for d in L for k, v in d.items() } 
+79
Aug 16 2018-10-16
source share

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

See also:

  • What is the purpose of .ChainMap collections?
+14
Jan 13 '16 at 5:50
source share
 >>> 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" does not match your output, because the dicts are unordered

if dicts can have more than one key / value

 >>> dict(j for i in L for j in i.items()) 
+5
Aug 16 '10 at 16:38
source share

For flat dictionaries, you can do this:

 from functools import reduce reduce(lambda a, b: dict(a, **b), list_of_dicts) 
+3
Apr 16 '13 at 22:36
source share
 dict1.update( dict2 ) 

This is asymmetric because you need to choose what to do with duplicate keys; in this case, dict2 overwrite dict1 . Exchange them differently.

EDIT: Ah, sorry, didn't see this.

This can be done in one expression:

 >>> from itertools import chain >>> dict( chain( *map( dict.items, theDicts ) ) ) {'a': 1, 'c': 1, 'b': 2, 'd': 2} 

There is no credit for this last!

However, I would say that it could be more Pythonic (explicit> implicit, flat> nested) to do this with a simple for loop. YMMV.

+1
Aug 16 2018-10-16T00:
source share
 >>> 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 that it works with multiple entries. In addition, the dicts keys in the list will later overwrite the same key from the earlier dict.

0
Aug 16 '10 at 16:59
source share

You can use the join function of the funcy library:

 from funcy import join join(list_of_dicts) 
0
Jun 04 '14 at 21:05
source share

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

dic2 {'Jose': 23, 'Marcos': 22, 'Patricia': 25, 'Tomas': 36, 'Paco': 22, 'Maria': 12}

0
Oct 26 '14 at 22:55
source share



All Articles