Skip to main content
 首页 » 编程设计

python之将字典值匹配回字典

2024年11月01日7softidea

我正在对两个字典执行数学运算,我想获取这些字典的输出并将它们映射回另一个字典。

我有一些工作代码可以输出我的预期值,但不会输出到我感兴趣的键:值对中。

我有两个字典:

dict1 
{'outer': {'word1':0.1234, 'word2':0.4321, 'word3':0.4567 } } 
dict2 
{'word1':2.222,'word3':3.567,'word2':2.123} 
 

我有这段代码可以将 word1 的值与各自字典中的 word1 的值相乘:

new_dict=dict() 
pkeys=dict1.keys() 
for key in pkeys: 
    for entry in dict1[key]: 
        new_dict[entry]=  dict1[key][entry] * dict2[entry] 

new_dict 包含正确的输出:'word1': 0.27419,但我似乎无法将其恢复为

中的格式
dict1: {'outer':{'word1':0.27419, 'word2':0.91734 }  

请您参考如下方法:

您可以使用dict.setdefault 方法在迭代中为当前键下的new_dict 初始化一个子字典。

改变:

new_dict[entry]=  dict1[key][entry] * dict2[entry] 

到:

new_dict.setdefault(key, {})[entry]=  dict1[key][entry] * dict2[entry]