Python sort dictionary by value in descending order then sort subgroups in ascending order?

Question:

Sample dict:

{'zed': 3, 'revenge': 3, 'laila': 3, 'bubo': 3, 'adele': 3, 'robert': 2, 'gia': 2, 'cony': 2, 'bandit': 2, 'anita': 2}

I want to sort these players by their score in descending order, so the scores with 3 goes first. But if there are more players with the same score, they should be arranged alphabetically, so the result should look like this:

{'adele': 3, 'bubo': 3, 'laila': 3, 'revenge': 3, 'zed': 3, 'anita': 2, 'bandit': 2, 'cony': 2, 'gia': 2, 'robert': 2}

Asked By: user916358

||

Answers:

You could use sorted along with dict.items:

d = {'zed': 3, 'revenge': 3, 'laila': 3, 'bubo': 3, 'adele': 3, 'robert': 2, 'gia': 2, 'cony': 2, 'bandit': 2, 'anita': 2}
sorted_d = dict(sorted(d.items(), key=lambda kvp: (-kvp[1], kvp[0])))
print(sorted_d)

Output:

{'adele': 3, 'bubo': 3, 'laila': 3, 'revenge': 3, 'zed': 3, 'anita': 2, 'bandit': 2, 'cony': 2, 'gia': 2, 'robert': 2}
Answered By: Sash Sinha
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.