Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two dictionaries into one with the same keys?

I've looked through a few of the questions here and none of them seem to be exactly my problem. Say I have 2 dictionaries, and they are dict1

{'A': 25 , 'B': 41, 'C': 32}

and dict 2

{'A':21, 'B': 12, 'C':62}

I'm writing a program where I need to combine these to one dictionary finaldict

{'A': [25 , 21], 'B': [41, 12], 'C': [32, 62]}

Any help is much appreciated, I've been working on this and getting nowhere for a while now

like image 764
seanscal Avatar asked Sep 01 '25 01:09

seanscal


2 Answers

This is a generic version. This can be used to create a dictionary with values as a list, even if the key is present in only one of them.

dic1 = {'A': 25, 'B': 41, 'C': 32}
dic2 = {'A': 21, 'B': 12, 'C': 62}
result = {}
for key in (dic1.keys() | dic2.keys()):
    if key in dic1: result.setdefault(key, []).append(dic1[key])
    if key in dic2: result.setdefault(key, []).append(dic2[key])

print(result)

Output

{'A': [25, 21], 'C': [32, 62], 'B': [41, 12]}

If you are using Python 2, for loop has to be changed like this:

for key in (dic1.viewkeys() | dic2.keys()):
like image 108
thefourtheye Avatar answered Sep 02 '25 13:09

thefourtheye


As you know that your two dictionaries will always have the same keys, you could use:

finaldict = {key:(dict1[key], dict2[key]) for key in dict1}

to combine them, where each value would be a tuple of the values from the source dictionaries.

like image 23
jonrsharpe Avatar answered Sep 02 '25 14:09

jonrsharpe