按值升序对字典排序,按键按降序对字典排序 [英] Sort a dictionary by values in ascending order and by keys in descending order
问题描述
我正在尝试对字典进行排序,我要遵循的顺序是,首先,字典应该按值以升序进行排序,如果两个或多个键的值相等,那么我想对字典进行排序通过键按降序排列.
I am trying to sort a dictionary, the order which I want to follow is that first, the dictionary should be sorted in increasing order by values and if the values for two or more keys are equal then I want to sort the dictionary by the keys in descending order.
这是代码:
dictionary = {0: 150, 1: 151, 2: 150, 3: 101, 4: 107}
print(sorted(dictionary.items(), key=lambda x: (x[1], x[0])))
我希望输出如下: [(3,101),(4,107),(2,150),(0,150),(1,151)]
但是输出是: [(3,101),(4,107),(0,150),(2,150),(1,151)]
推荐答案
由于此处的值是数字,因此可以使用否定键,其作用与反转排序顺序的作用相同:
Because the values are numeric here, you can use negation as having the same effect as reversing the sort order:
sorted(dictionary.items(), key=lambda x: (x[1], -x[0]))
对于更通用的情况,您不能依赖于数字值,这是一种可能的方法,尽管可能有更好的方法.
For the more generic case where you can't rely on the values being numeric, here is a possible approach, although there may be a better way.
from functools import cmp_to_key
def cmp(a, b):
# https://stackoverflow.com/a/22490617/13596037
return (a > b) - (a < b)
def cmp_items(a, b):
"""
compare by second item forward, or if they are the same then use first item
in reverse direction (returns -1/0/1)
"""
return cmp(a[1], b[1]) or cmp(b[0], a[0])
dictionary = {0: 150, 1: 151, 2: 150, 3: 101, 4: 107}
print(sorted(dictionary.items(), key=cmp_to_key(cmp_items)))
这篇关于按值升序对字典排序,按键按降序对字典排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!