2

Let's say I have the following tuple (python):

scores = {'player1':200,'player2':300,'player3':150}

The reason I have one tuple and not a list of tuples is so that I can update the scores very easily, i.e.

scores['player1'] += 50

How can I get the player that scored the highest? Or sort the players by their scores:

[player2, player1, player3]

Thanks.

TheProofIsTrivium
  • 768
  • 2
  • 11
  • 25

1 Answers1

1

You might want to look at the built-in sorted function: http://docs.python.org/2/library/functions.html#sorted

sorted(iterable[, cmp[, key[, reverse]]])

You could specify the item of dictionary as key, and set reverse to True so that you could get a list of scores in descending order.

>>> scores = {'player1':200,'player2':300,'player3':150}
>>> max_score = sorted(scores, key=scores.__getitem__, reverse=True)[0]
>>> max_score
'player2'

As a side note, scores.__getitem__(i) is roughly the same as scores[i].

>>> scores.__getitem__('player1')
200
>>> scores['player1']
200
Mingyu
  • 31,751
  • 14
  • 55
  • 60