简体   繁体   English

Python按词降序排序字典,然后按字母顺序排列

[英]Python sort dictionary by descending values and then by keys alphabetically

I have the following dictionary: 我有以下字典:

fruits = {
    "apple": 5,
    "Apple": 5,
    "orange": 5,
    "strawberry": 3,
    "blueberry": 1
}

I need to print out a list of the two keys with the highest values. 我需要打印出具有最高值的两个键的列表。 Ties need to be broken alphabetically AZ with capital letters taking precedence over lowercase ones. 关系需要按字母顺序打开AZ,大写字母优先于小写字母。 Running the following sorts by the counts, but doesn't break the ties: 通过计数运行以下排序,但不会破坏关系:

popular_fruits = sorted(fruits, key=fruits.get, reverse=True)
print(popular_fruits[0:2])

How can I accomplish this? 我怎么能做到这一点?

You can use something like this: 你可以使用这样的东西:

popular_fruits = sorted(fruits, key=lambda x: (-fruits[x], x))
print(popular_fruits[0:2])

EDIT: 编辑:

A negation before fruits[x] is used to reverse the decreasing numeric ordering and in case of a tie the order is determined by the second argument of the tuple (alphabetically). fruits[x]之前的否定用于反转递减的数字排序,并且在平局的情况下,顺序由元组的第二个参数(按字母顺序)确定。

One cannot simply use sorted(fruits, key=lambda x: (fruits[x], x), reverse=True) because it will reverse ordering for both tuple elements, but we need to do it for the first element only. 人们不能简单地使用sorted(fruits, key=lambda x: (fruits[x], x), reverse=True)因为它会反转两个元组元素的排序,但我们只需要为第一个元素执行此操作。

You can do secondary sorting by using a tuple. 您可以使用元组进行二级排序。 I used -1 * the value to reverse it. 我使用-1 *值来反转它。 "Capitals first" is the default sorting order for Python. “Capitals first”是Python的默认排序顺序。

This is wrong even though it got some upvotes: 这是错误的,即使它有一些赞成:

popular_fruits = sorted(fruits, key = lambda x: (-1 * x[1], x[0]))

# ['Apple', 'apple']

It should be as taras posted: 它应该像taras张贴的那样:

popular_fruits = sorted(fruits, key = lambda x: (-fruits[x], x))

I was sorting by the first and second letter and happened to give the first two items in order correctly but is actually completely wrong. 我正在按第一个和第二个字母排序,碰巧正确地给出前两个项目,但实际上是完全错误的。 I'll keep this up if people think it is useful to see an error that you can make by confusing a dict for a list of lists/tuples. 如果人们认为通过混淆列表/列表列表的dict来查看错误是有用的,我会继续这样做。

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

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