Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading