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

时间:2015-06-17 04:14:19

标签: python-2.7 dictionary lookup

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

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,'薪水':1927262.26}

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

1 个答案:

答案 0 :(得分:0)

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

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}