How do I return a new dictionary if the keys in one dictionary, match the keys in another dictionary?

  • A+
Category:Languages

Currently, I have a dictionary, with its key representing a zip code, and the values are also a dictionary.

d = { 94111: {'a': 5,  'b': 7,  'd': 7},        95413: {'a': 6,  'd': 4},        84131: {'a': 5,  'b': 15, 'c': 10, 'd': 11},        73173: {'a': 15, 'c': 10, 'd': 15},        80132: {'b': 7,  'c': 7,  'd': 7} } 

And then a second dictionary, which associates which state the zip code belongs to.

states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"} 

If the zip code in the dictionary states matches one of the keys in db then it would sum up those values and put it into a new dictionary like the expected output.

Expected Output:

{'TX': {'a': 10, 'b': 22, 'd': 18, 'c': 10}, 'AL': {'a': 21, 'd': 26, 'c': 17, 'b': 7}} 

I've been stuck on how to proceed for almost an hour now and have absolutely no clue. So far this is the direction I am looking to go into but i'm not sure when both the keys match, how to create a dictionary that will look like the expected output.

def zips(d, states):     result = dict()     for key, value in db.items():         for keys, values in states.items():             if key == keys:   zips(d, states) 

 


Using collections module

Ex:

from collections import defaultdict, Counter  d = { 94111: {'a': 5,  'b': 7,  'd': 7},        95413: {'a': 6,  'd': 4},        84131: {'a': 5,  'b': 15, 'c': 10, 'd': 11},        73173: {'a': 15, 'c': 10, 'd': 15},        80132: {'b': 7,  'c': 7,  'd': 7} }  states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}  result = defaultdict(Counter) for k,v in d.items():     if k in states:         result[states[k]] += Counter(v) print(result) 

Output:

defaultdict(<class 'collections.Counter'>, {'AL': Counter({'d': 26, 'a': 21, 'c': 17, 'b': 7}),  'TX': Counter({'b': 22, 'd': 18, 'a': 10, 'c': 10})}) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: