I have two 2D python dictionaries, and I want to get a single 2D dictionary where the keys are the union of the first two dictionaries' keys and the values a concatenation of the 1d dictionary. In case of duplicate keys in the 1D dictionaries, I would like to have the sum of their values.
So, supposing that I've :
dict1 = { 1: {2: 0.1, 3: 0.3, 4: 0.4} ,
2 :{1: 0.2, 3: 0.3, 4: 0.5} }
dict2 = { 2: {1: 0.1, 3: 0.8, 5: 0.4} ,
3 :{1: 0.2, 2: 0.8, 4: 0.5} }
what I expect to have is:
merged_dict = { 1: {2: 0.1, 3: 0.3, 4: 0.4} ,
2 :{1: 0.3, 3: 1.1, 4: 0.5 , 5: 0.4} ,
3: {1: 0.2, 2: 0.8, 4: 0.5} }
I'm currently using python 3.2.3
Nothing fancy here but you can always do something like:
merged_dict = dict1.copy()
for key, val in dict2.iteritems():
if key not in dict1:
merged_dict[key] = val
else:
for key2, val2 in val.iteritems():
if key2 not in dict1[key]:
merged_dict[key][key2] = val2
else:
merged_dict[key][key2] += val2
(sorry that's python 2.7)
Also, if you want to use defaultdict
:
from collections import defaultdict
merged_dict = defaultdict(dict)
for key, val in dict1.iteritems():
merged_dict[key] = defaultdict(int, val)
for key, val in dict2.iteritems():
if key not in merged_dict:
merged_dict[key] = defaultdict(int, val)
else:
for key2, val2 in val.iteritems():
merged_dict[key][key2] += val2
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments