Search code examples
pythondictionaryenumerate

Python - Difference between getting a value in dictionary using those two methods


I'm beginner in Python, and making a words game. And have a dictionary of {"player 1":0, "player 2":0} that keeps track of the two players score.

I have a play again option so i need to always store the score into that dictionary.

But when i retrieve this dictionary values after each round using this :

for value, index in enumerate(players):
      print index, " : ", value

I get this just no matter how many rounds are played :

Player 2 : 0
Player 1 : 1

But when i use :

for index in players:
     print index, " : ", players.get(index, 0)

I get the actual values that i want.

My question is what's the difference between getting values using the two methods ?


Solution

  • enumerate is iterating over the dictionary, but by default, you iterate over the keys only:

    iter(d)

    Return an iterator over the keys of the dictionary. This is a shortcut for iterkeys().

    What you probably want is either items() or values().

    items()

    Return a copy of the dictionary’s list of (key, value) pairs.

    values()

    Return a copy of the dictionary’s list of values. See the note for dict.items().

    I think you want this:

    for name, score in players.items():
          print name, " : ", score
    

    Or maybe:

    for index, (name, score) in enumerate(players.items()):
          print index, " : ", name, " : ", score
    

    Just to demonstrate the other two possibilities, this method looks up all of the names:

    for name in players: # or players.keys()
        print name
    

    And this looks up scores (without names):

    for score in players.values():
        print score