Python 如何按值(DESC)然后按键(ASC)对字典进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15371691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:56:07  来源:igfitidea点击:

How to sort a dictionary by value (DESC) then by key (ASC)?

pythonsortingkey

提问by ecr

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

就在发现了惊人的之后sorted(),我又陷入了困境。

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, butif two elements where to have same value, then by ascending order of key.

问题是我有一个表单的字典,string(key) : integer(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.

这是因为它对值和键都进行了反向排序。我需要不倒转的钥匙。

采纳答案by Lev Levitsky

Something like

就像是

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)]

回答by Sergey Zakharov

  • Dictionaries can't be sorted directly, so you need to instead sort the items(), the list of tuples containing key/value pairs.

  • Since you want to sort by the value field, then the key fields, it is necessary to extract those field from the tuple for use as the sort key using operator.itemgetterwhich gets the specified field.

  • Lastly, to sort descending on one field and descending on another, do two passes, first sorting by the secondary key ascending, and then another pass sorting by the primary key descending. This step relies on Python's sort stability.

  • 字典不能直接排序,因此您需要对items(),即包含键/值对的元组列表进行排序。

  • 由于您要按值字段排序,然后是键字段,因此有必要从元组中提取这些字段用作排序键,使用operator.itemgetter它获取指定字段。

  • 最后,要对一个字段进行降序排序并在另一个字段上进行降序排序,请执行两次传递,首先按辅助键升序排序,然后再按主键降序排序。这一步依赖于 Python 的排序稳定性

For example:

例如:

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

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

See the Python Sorting-HOWTO guidefor more details.

有关更多详细信息,请参阅Python Sorting-HOWTO 指南