简体   繁体   English

Python 按值按降序对字典进行排序,然后按升序对子组进行排序?

[英]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.我想按他们的分数降序对这些球员进行排序,所以分数为 3 排在第一位。 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. items您可以将sorteddict. items dict. items : 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: Output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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