0

Say I'm tracking the score in a paper/scissors/rock game, and the player's used both paper and rock twice, giving the dict tracking the moves {'rock': 2, 'paper': 2, 'scissors': 0} I call print(sorted(dict, key=dict.get, reverse=True)), returning the list ['rock', 'paper', 'scissors']. Why is it in this order and not ['paper', 'rock', 'scissors']?

crispin
  • 1
  • 2
  • 1
    You are sorting by value so what order do you expect? – Padraic Cunningham Sep 08 '16 at 00:21
  • 1
    Though you are sorting by value, in case of a tie, `sorted` will do a stable sort. This means whatever dictionary item is "first" will be first in the produced list. However, a Python dictionary isn't supposed to have a concept of order. There are a lot of questions on Stack Overflow that address the concept (or lack thereof) of dictionary order. – Karin Sep 08 '16 at 00:26
  • What you want is `sorted(d, key=lambda x:[-d[x], x])`, sort by negating the value and break ties with the key name. – Padraic Cunningham Sep 08 '16 at 00:26

0 Answers0