EDIT
i have:
[{'a':1},{'b':2},{'c':1},{'d':2}]
the output should be:
{'a':1,'b':2,'c':1,'d':2}
EDIT
i have:
[{'a':1},{'b':2},{'c':1},{'d':2}]
the output should be:
{'a':1,'b':2,'c':1,'d':2}
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.
>>> 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())
This works for dictionaries of any length:
>>> result = {}
>>> for d in L: result.update(d)
...
{'a':1,'c':2,'b':1,'d':2}
And as generator-oneliner:
dict((k,v) for d in L for (k,v) in d.items())
Edit: As pointed out by katrielalex, dictionary comprehension:
{ k: v for d in L for k, v in d.items() }
is even better. OTOH they are Python3-only, so they may not be available to you.
This handles all the subdicts in your list, even if they have multiple items:
dict(sum((d.items() for d in L), []))
But I think update() is preferred:
>>> dd = {}
>>> for d in L: dd.update(d)
>>> 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.