Iterating Over Dictionary Key Values Corresponding to List in Python

258,904

Solution 1

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)

Solution 2

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)

Solution 3

Dictionaries have a built in function called iterkeys().

Try:

for team in league.iterkeys():
    runs_scored = float(league[team][0])
    runs_allowed = float(league[team][1])
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
    print win_percentage

Solution 4

Dictionary objects allow you to iterate over their items. Also, with pattern matching and the division from __future__ you can do simplify things a bit.

Finally, you can separate your logic from your printing to make things a bit easier to refactor/debug later.

from __future__ import division

def Pythag(league):
    def win_percentages():
        for team, (runs_scored, runs_allowed) in league.iteritems():
            win_percentage = round((runs_scored**2) / ((runs_scored**2)+(runs_allowed**2))*1000)
            yield win_percentage

    for win_percentage in win_percentages():
        print win_percentage

Solution 5

List comprehension can shorten things...

win_percentages = [m**2.0 / (m**2.0 + n**2.0) * 100 for m, n in [a[i] for i in NL_East]]
Share:
258,904
Burton Guster
Author by

Burton Guster

Updated on August 31, 2020

Comments

  • Burton Guster
    Burton Guster over 3 years

    Working in Python 2.7. I have a dictionary with team names as the keys and the amount of runs scored and allowed for each team as the value list:

    NL_East = {'Phillies': [645, 469], 'Braves': [599, 548], 'Mets': [653, 672]}
    

    I would like to be able to feed the dictionary into a function and iterate over each team (the keys).

    Here's the code I'm using. Right now, I can only go team by team. How would I iterate over each team and print the expected win_percentage for each team?

    def Pythag(league):
        runs_scored = float(league['Phillies'][0])
        runs_allowed = float(league['Phillies'][1])
        win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
        print win_percentage
    

    Thanks for any help.

  • StackExchange saddens dancek
    StackExchange saddens dancek over 12 years
    @BurtonGuster: Whenever you think an answer worthy, please upvote (click the "up" button on the left side of the post)! That way you're helping the community, too!
  • Sergey
    Sergey over 8 years
    dict.iteritems() was removed since Python3. You should use dict.items() instead
  • Abbas Gadhia
    Abbas Gadhia about 8 years
    dict.iterkeys() was also removed in Python 3. You should use dict.keys() instead
  • Zachary Ryan Smith
    Zachary Ryan Smith almost 6 years
    dict.itervalues() was also removed in Python 3. You should use dict.values() instead
  • DoronS
    DoronS over 3 years
    What about checking if a key available in a dict on if statement ? is it also the same?