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
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()):
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With