Python 在 2 个词典之间进行查找

Python do a lookup between 2 dictionaries

我正在尝试总结两个词典如下:

mydict = {41100: 'Health Grant',
 50050: 'Salaries',
 50150: 'Salaries',
 50300: 'Salaries'};
mytb = {'': '',
 41100: -3,450,200.40,
 50050: 1,918,593.96,
 50150: 97.50,
 50300: 8,570.80}

我的输出应该是:

{ 'Health Grant': -3450200.40, 'Salaries': 1927262.26 }

你能帮忙编写 for 循环代码吗?

只需迭代第一个字典的键和值,然后添加与相同键对应的第二个字典的值。

mydict = {41100: 'Health Grant', 50050: 'Salaries', 50150: 'Salaries', 50300: 'Salaries'};
mytb = {'': '', 41100: -3450200.40, 50050: 1918593.96, 50150: 97.50, 50300: 8570.80}

result = {}
for key, value in mydict.items():
    result[value] = result.get(value, 0) + mytb[key]

或使用collections.defaultdict:

from collections import defaultdict
result = defaultdict(int)
for key, value in mydict.items():
    result[value] += mytb[key]

在这两种情况下,result 将是 {'Health Grant': -3450200.4, 'Salaries': 1927262.26}