Python do a lookup between 2 dictionaries

627 views Asked by At

I am trying to summarise two dictionaries as follows:

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}

My output should be:

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

Can you help with coding the for loop code pls?

1

There are 1 answers

0
tobias_k On BEST ANSWER

Just iterate the keys and values of the first dict and add the values from the second dict corresponding to the same key.

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]

Or using collections.defaultdict:

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

In both cases, result will be {'Health Grant': -3450200.4, 'Salaries': 1927262.26}