Quiz 18 Solution

Dictionaries

The task can be accomplished with the following code.

state2pop = {}
for z,s in zip2state.items():
    state2pop[s] = state2pop.get(s, 0) + zip2pop[z]     # previous population plus additional population

Note well that the use of get method above allows us to gracefully handle a case when a state is first encountered, with its previous population presumed to be zero at that time. Without that method, we coudl express this logic as follows:

state2pop = {}
for z,s in zip2state.items():
    if s in state2pop:
        state2pop[s] += zip2pop[z]
    else:
        state2pop[s] = zip2pop[z]


Last modified: Tuesday, 27 November 2018