Reputation:
I want to merge the values of two dictionaries by their keys. Example:
d1 = {'a':1, 'b':2, 'c':3}
d2 = {'a':2, 'b':[2,3], 'd':3}
desired output:
{'a': [1, 2], 'b': [2, 2, 3], 'c': [3], 'd': [3]}
What I have so far is
d12 = {}
for d in (d1, d2):
for k,v in d.items():
d12.setdefault(k, []).append(v)
which produces
d12 = {'a': [1, 2], 'b': [2, [2, 3]], 'c': [3], 'd': [3]}
not desired output.
I searched a bit on SO and found that this post answers my question if only it didn't throw up TypeError: can only concatenate tuple (not "int") to tuple.
Upvotes: 4
Views: 123
Reputation: 411
Only using append
,
d1 = {'a':1, 'b':2, 'c':3}
d2 = {'a':2, 'b':[2,3], 'd':3}
d12 = {}
for d in (d1, d2):
for k,v in d.items():
if not isinstance(v, list):
d12.setdefault(k, []).append(v)
else:
for i in v:
d12.setdefault(k, []).append(i)
print(d12)
Upvotes: 0
Reputation: 71620
You could also try using dict.update
with a lambda
flatten function and dict.get
:
dct = {}
for i in d1.keys() | d2.keys():
flatten = lambda *n: [e for a in n for e in (flatten(*a) if isinstance(a, (tuple, list)) else (a,))]
l = flatten([i for i in [d1.get(i, None), d2.get(i, None)] if i])
dct.update({i: l})
print(dct)
Output:
{'b': [2, 2, 3], 'a': [1, 2], 'c': [3], 'd': [3]}
Upvotes: 0
Reputation: 59444
The problem is your values are sometimes int
s and sometimes list
s. You must check the data type and either append
or extend
accordingly:
for k, v in d.items():
if isinstance(v, list):
d12.setdefault(k, []).extend(v)
else:
d12.setdefault(k, []).append(v)
Upvotes: 7