Merging two dictionaries with nested arrays

六月ゝ 毕业季﹏ 提交于 2019-12-01 14:40:09

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 sets.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!