Iterating Over Dictionary Key Values Corresponding to List in Python
You have several options for iterating over a dictionary.
If you iterate over the dictionary itself (for team in league
), you will be iterating over the keys of the dictionary. When looping with a for loop, the behavior will be the same whether you loop over the dict (league
) itself, or league.keys()
:
for team in league.keys():
runs_scored, runs_allowed = map(float, league[team])
You can also iterate over both the keys and the values at once by iterating over league.items()
:
for team, runs in league.items():
runs_scored, runs_allowed = map(float, runs)
You can even perform your tuple unpacking while iterating:
for team, (runs_scored, runs_allowed) in league.items():
runs_scored = float(runs_scored)
runs_allowed = float(runs_allowed)
You can very easily iterate over dictionaries, too:
for team, scores in NL_East.iteritems():
runs_scored = float(scores[0])
runs_allowed = float(scores[1])
win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
print '%s: %.1f%%' % (team, win_percentage)