I have a dictionary for each state in the continental US. Each has a key-value pair that I have to ultimately merge and add into a single key-value pair. It looks like this:
Indiana = {Year:2018, Total:102 Year:2017, Total: 84....}
Alabama = {Year:2018, Total: 115 Year: 2017, Total:116....}
Colorado = {Year:2018, Total: 71 Year:2017, Total: 76....}
What I want is to merge the dictionaries like this:
Continentals = {Year:2018, Total: 102 115 71 Year: 2017, Total: 84 116 76.....}
Is there a way to merge all these dictionaries into one dictionary while also summing the totals for each year together?
CodePudding user response:
The dictionaries you've provided would overwrite their own values with each entry. You would need to rearrange your dictionary structure to be closer to:
indiana = {2018: total_value, 2017: total_value}
alabama = {2018: total_value, 2017: total_value}
...
This way you could simply loop through your list of state dicts and update a new dict as you iterate.
continentals = {}
for state in list_of_states:
for year, total_value in state.items():
continentals[year] = continentals.get(year, 0) total_value
CodePudding user response:
Using Jesse's structure proposition, you can even do this with a Counter
:
from collections import Counter
indiana = {2018: total_value, 2017: total_value}
alabama = {2018: total_value, 2017: total_value}
c = Counter()
for d in[indiana, alabama]:
c.update(d)