2
votes

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

1
what have you tried? this is not a site where people just write code for you.Julien Spronck
The first experiment was something like: merged_dict = dict1.update(dict2) as I've seen for 1d dictionary but it seems that only copies the first dictionary values() So I've tried another approach this too suggested in this site, that consists in mergeddict = dict(d1,**d2) that doesn't work since it expects strings but I've not strings. Finally now I'm doing something like: for item in for item in set( d1.keys()) | set( d2.keys() ): merged[item] = d1[item].update( d2[item] )LeoCella

1 Answers

2
votes

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