Home > Back-end >  Concatenating two dictionaries together
Concatenating two dictionaries together

Time:06-24

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]}

CodePudding user response:

You can use:

{k: [v1, v2] for k, v1, v2 in zip(dmx.keys(), dmx.values(), dx.values())}

If the keys aren't in the same order in both dictionaries (since dictionaries are insertion-ordered in Python 3.7 ), then you can use the following instead:

{k: [dmx[k], dx[k]] for k in dmx.keys()}

Both of these output:

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

CodePudding user response:

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]}
  • Related