Home > Software design >  Python sort dictionary by value in descending order then sort subgroups in ascending order?
Python sort dictionary by value in descending order then sort subgroups in ascending order?

Time:08-11

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}

CodePudding user response:

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}
  • Related