如何按值(DESC)然后按键(ASC)对字典排序? [英] How to sort a dictionary by value (DESC) then by key (ASC)?

查看:75
本文介绍了如何按值(DESC)然后按键(ASC)对字典排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就在发现惊人的sorted()之后,我再次陷入困境.

Just after discovering the amazing sorted(), I became stuck again.

问题是我有一个格式为string(key) : integer(value)的字典,我需要按其整数值的降序对它进行排序,但是如果两个元素的值相同,则通过升序进行排序键的顺序.

The problem is I have a dictionary of the form string(key) : integer(value) and I need to sort it in descending order of its integer values, but if two elements where to have same value, then by ascending order of key.

一个更清晰的例子:

d = {'banana':3, 'orange':5, 'apple':5}
out: [('apple', 5), ('orange', 5), ('banana', 3)]

做完一些研究后,我得出了这样的结论:

After doing some research I arrived at something like:

sorted(d.items(), key=operator.itemgetter(1,0), reverse=True)
out: [('orange', 5), ('apple', 5), ('banana', 3)]

这是因为它对值和键都进行了反向排序.我需要不撤消钥匙.

This is because it's reverse-sorting both the value and the key. I need the key to be un-reversed.

推荐答案

类似

In [1]: d = {'banana': 3, 'orange': 5, 'apple': 5}

In [2]: sorted(d.items(), key=lambda x: (-x[1], x[0]))
Out[2]: [('apple', 5), ('orange', 5), ('banana', 3)]

这篇关于如何按值(DESC)然后按键(ASC)对字典排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆