Question

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 ?

Was it helpful?

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

OTHER TIPS

The enumerate method gives back index, value pairs. It appears that for a dictionary enumerate is enumerating the key collection (which is why you see the keys).

In here,

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

value is the counter of enumerate, that is why you're always going to see value goes from 0,1,2,3,...

I think what you really wanted is

for index, value in enumerate(players): 
    print value, " : ", players[value] # .get works as well

Enumerating dictionary generally makes little sense because dictionary are unordered.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top