Reputation: 311
I'm trying to sort a dictionary where the value is a list of two elements where I need to sort the second element (a number) in descending order. I then want the key to be in descending order as well. I thought this would do it..
users = sorted(users.items(), key=lambda x: (x[1][1], x[0]), reverse=True)
and while the list is in descending order of the number the names are still in ascending order whenever there is a tie. Should I be handling it differently?
Upvotes: 0
Views: 127
Reputation: 7186
At least for me, your code works as expected:
users = {"a": (0, 0), "b": (0, 1), "c": (0, 1)}
sorted(users.items(), key=lambda x: (x[1][1], x[0]), reverse=True)
[('c', (0, 1)), ('b', (0, 1)), ('a', (0, 0))]
It first sorts by the value in the second position and for a tie it sorts by the key.
Upvotes: 1