4

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.

Selcuk
  • 57,004
  • 12
  • 102
  • 110

3 Answers3

7

The problem is your values are sometimes ints and sometimes lists. 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)
Selcuk
  • 57,004
  • 12
  • 102
  • 110
0

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]}
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

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)
Subham
  • 397
  • 1
  • 6
  • 14