Concatenating two dictionaries together

I am very confused as to how to solve the issue, since I run into a lot of errors such as such as TypeError: string indices must be integers.

Given:

dmx={'a': 0, 'b': 3, 'c': 9, 'd': 2, 'e': 4}
dx={'a': 2, 'b': 4, 'c': 9, 'd': 5, 'e': 1}

I want to produce:

d={'a': [2,0], 'b': [4,3], 'c': [9,9], 'd': [5,2] ,'e': [1,4]}

>Solution :

To have a generic solution for any number of dictionaries, you can use setdefault:

out = {}
for d in [dmx, dx]:
    for k,v in d.items():
        out.setdefault(k, list()).append(v)

Or use collections.defaultdict

from collections import defaultdict

out = defaultdict(list)

for d in [dmx, dx]:
    for k,v in d.items():
        out.append(v)

Output:

{'a': [0, 2], 'b': [3, 4], 'c': [9, 9], 'd': [2, 5], 'e': [4, 1]}

Leave a Reply