gpt4 book ai didi

python - 合并两个二维字典python

转载 作者:太空宇宙 更新时间:2023-11-04 03:23:52 28 4
gpt4 key购买 nike

我有两个 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

最佳答案

这里没什么特别的,但你总是可以做类似的事情:

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

关于python - 合并两个二维字典python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33731985/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com