[英]Python sorting dictionaries: Key [Ascending] and then Value [Descending]
I have looked for ages and have found no actual answers because I can't see any that start with an ascending key and then by a descending value. 我已经查找了很久并找不到实际的答案,因为我看不到任何以升序键开头,然后是降序值。
An example to make it clearer: 一个让它更清晰的例子:
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.
我需要钥匙不要反转。
I'd really appreciate some help here. 我真的很感激这里的一些帮助。 Thanks in advance!
提前致谢!
What you are asking is not possible as stated. 你所要求的是不可能的。 Not only are dictionaries unordered (which can be overcome with an
OrderedDict
), but their keys are unique, which means the idea of sorting by key and then by value is nonsensical. 不仅字典无序(可以用
OrderedDict
克服),但它们的键是唯一的,这意味着按键然后按值排序的想法是荒谬的。
What you want is to either use a list of tuples instead, or to use an OrderedDict
in which the values are lists (so that they can have multiple values and be sorted.) 你想要的是使用一个元组列表,或者使用一个
OrderedDict
,其中值是列表(这样它们可以有多个值并被排序。)
List of tuples: 元组列表:
x = [(1,7), (5,3), (8,3), (1,4), (12,4), (12,7), (12,5)]
x.sort(key=itemgetter(1), reverse=True)
x.sort(key=itemgetter(0))
# result: [(1, 7), (1, 4), (5, 3), (8, 3), (12, 7), (12, 5), (12, 4)]
Like others say, keys are unique in dictionaries, so if you sort d.items() by key, there is no more sorting to do. 像其他人说的那样,键在字典中是唯一的,所以如果你按键对d.items()进行排序,就不再需要进行排序了。 But what if you want to sort first by descending value and then by ascending key?
但是如果你想先按降序值然后按升序键排序呢?
out = list(sorted(d.items(), key=(lambda item: (-item[1],item[0])))) out = list(已排序(d.items(),key =(lambda item:( - item [1],item [0]))))
Result: [('apple', 5), ('orange', 5), ('banana', 3)] 结果:[('apple',5),('orange',5),('banana',3)]
Explanation: When sorting tuples, the elements are considered in sequence. 说明:对元组进行排序时,将按顺序考虑元素。 In the expression above I have used a new tuple derived from the original tuple item, to flip the order and also flip the sign of the number.
在上面的表达式中,我使用了从原始元组项中派生的新元组,以翻转顺序并翻转数字的符号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.