I have 2 dictionaries
a = {'I': [1,2], 'II': [1,2], 'III': [1,2]}
b = {'I': [3,4], 'II': [3,4], 'IV': [3,4]}
how can i merge them such that i get the following result
c = merge_dicts(a,b)
where c is {'I': [1,2,3,4], 'II': [1,2,3,4], 'III': [1,2], 'IV': [3,4]}
Is there a good pythonic way of doing this?
Note that I am a python newbie, even though I am using words like pythonic. Thanks in advance.
If you need ALL values:
from itertools import chain
from collections import defaultdict
a = {'I': [1,2], 'II': [1,2], 'IV': [1,2]}
b = {'I': [3,4], 'II': [3,4], 'V': [3,4]}
d = defaultdict(list)
for key, value in chain(a.iteritems(), b.iteritems()):
d[key].extend(value)
d
Output:
defaultdict(<type 'list'>, {'I': [1, 2, 3, 4], 'II': [1, 2, 3, 4], 'V': [3, 4], 'IV': [1, 2]})
Are you sure they have the same keys? You could do:
c = dict( (k,a[k]+b[k]) for k in a )
Addition of lists concatenates so a[k] + b[k]
gives you something like [1,2]+[3,4]
which equals [1,2,3,4]
. The dict
constructor can take a series of 2-element iterables which turn into key
- value
pairs.
If they don't share the keys, you can use set
s.
aset = set(a)
bset = set(b)
common_keys = aset & bset
a_only_keys = aset - bset
b_only_keys = bset - aset
c = dict( (k,a[k]) for k in a_only_keys )
c.update( (k,b[k]) for k in b_only_keys )
c.update( (k,a[k]+b[k]) for k in common_keys )
>>> from collections import Counter
>>> class ListAccumulator(Counter):
... def __missing__(self, key):
... return []
...
>>> a = {'I': [1,2], 'II': [1,2], 'III': [1,2]}
>>> b = {'I': [3,4], 'II': [3,4], 'IV': [3,4]}
>>>
>>> ListAccumulator(a) + ListAccumulator(b)
Counter({'IV': [3, 4], 'I': [1, 2, 3, 4], 'II': [1, 2, 3, 4], 'III': [1, 2]})
>>> a = {'I': [1,2], 'II': [1,2]}
>>> b = {'I': [3,4], 'II': [3,4]}
>>> {key:a[key]+b[key] for key in a}
{'I': [1, 2, 3, 4], 'II': [1, 2, 3, 4]}
Note that this only works if they share keys exactly.
来源:https://stackoverflow.com/questions/12634452/merging-two-dictionaries-with-nested-arrays