简体   繁体   中英

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

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}

You could use sorted along with dict. :

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM