合并两个2D字典python

时间:2015-11-16 09:24:50

标签: python dictionary merge 2d

我有两个2D python词典,我想得到一个2D词典,其中键是前两个词典的联合'键和值是1d字典的串联。如果一维词典中有重复的键,我希望得到它们的值的总和。

所以,假设我已经:

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} }

我期望得到的是:

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} }

我目前正在使用python 3.2.3

1 个答案:

答案 0 :(得分:2)

这里没有什么花哨的东西,但你总是可以这样做:

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

(对不起,#python 2.7)

此外,如果您想使用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