pad11
pad11

Reputation: 311

Sorting a dictionary by value descending then key descending

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

Answers (1)

Graipher
Graipher

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

Related Questions