按值排序字典然后键 [英] Sorting a dictionary by value then key
问题描述
我可以按键或值排序,但我需要在一行中按值排序,然后是键.为了更好地解释这一点,我可以向您展示我的问题:
dict = {'apple': 2, 'banana': 3, 'almond':2 , 'beetroot': 3, 'peach': 4}
我希望我的输出按它们的值降序排序,然后按它们的键(按字母顺序)升序 (A-Z).导致这样一个列表:
输出:['peach', 'banana', 'beetroot', 'almond', 'apple']
到目前为止我知道的唯一方法是:
[v[0] for v in sorted(dict.items(), key=lambda(k,v): (v,k))]
输出:['almond', 'apple', 'banana', 'beetroot', 'peach']
因此它按升序对值进行了排序,并按字母顺序(A-Z)对键进行了排序.所以如果我扭转这个:
[v[0] for v in sorted(dict.items(), key=lambda(k,v): (v,k), reverse=True)]
输出:['peach', 'beetroot', 'banana', 'apple', 'almond']
它已按降序对值进行排序,并按字母顺序(Z-A)对键进行排序.
有没有一种方法可以按降序对值进行排序,按升序(即 A-Z)对键进行排序并获得我上面显示的输出?
您需要利用值是数字这一事实.
<预><代码>>>>[v[0] for v in sorted(d.iteritems(), key=lambda(k, v): (-v, k))]['桃子'、'香蕉'、'甜菜根'、'杏仁'、'苹果']I can sort by key or value, but I need it sorted by value, then key, in one line. To explain this better I can show you my problem:
dict = {'apple': 2, 'banana': 3, 'almond':2 , 'beetroot': 3, 'peach': 4}
I want my output to be sorted descending by their value and then ascending (A-Z) by their key (alphabetically). Resulting in such a list:
With the output of: ['peach', 'banana', 'beetroot', 'almond', 'apple']
The only way I know how to do it so far is:
[v[0] for v in sorted(dict.items(), key=lambda(k,v): (v,k))]
With the output of: ['almond', 'apple', 'banana', 'beetroot', 'peach']
So it has sorted the values in ascending order and the keys alphabetically in ascending order (A-Z). So if I reverse this:
[v[0] for v in sorted(dict.items(), key=lambda(k,v): (v,k), reverse=True)]
With the output of: ['peach', 'beetroot', 'banana', 'apple', 'almond']
It has sorted the values in descending order and the keys alphabetically in descending order (Z-A).
Is there a way I can sort the values in descending order and the keys in ascending order (i.e. A-Z) and get the output I showed above?
You need to take advantage of the fact that the values are numbers.
>>> [v[0] for v in sorted(d.iteritems(), key=lambda(k, v): (-v, k))]
['peach', 'banana', 'beetroot', 'almond', 'apple']
这篇关于按值排序字典然后键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!