Python 排序字典 : Key [Ascending] and then Value [Descending]

标签 python sorting

我已经找了很久,但没有找到实际的答案,因为我看不到任何以升序键开头然后以降序值开头的答案。

一个更清楚的例子:

d = {'banana':3, 'orange':5, 'apple':5}
out: [('apple', 5), ('orange', 5), ('banana', 3)]

在做了一些研究后,我得出了类似的结论:

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

这是因为它对值和键进行反向排序。我需要未反转的 key 。

我真的很感激这里的一些帮助。提前致谢!

最佳答案

你问的是不可能的。不仅字典是无序的(这可以用 OrderedDict 克服),而且它们的键是唯一的,这意味着先按键再按值排序的想法是荒谬的。

您想要的是改为使用元组列表,或者使用 OrderedDict,其中的值是列表(以便它们可以有多个值并进行排序。)

元组列表:

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

关于Python 排序字典 : Key [Ascending] and then Value [Descending],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35539265/

相关文章:

python - 是否可以将 Google 服务帐户限制为项目中的特定 BigQuery 数据集?

c++ - 如何修复此排序功能以对结构中的两个字段进行排序

python - python3 中的 pexpect.expect() 抛出错误 "must be in str , not bytes"

python - 是否有用于训练对数线性模型的 python 包?

python - 使用 eclipse 和 python/django 进行开发时个人/家庭使用的最佳版本控制系统

java - 这个特定的合并排序程序是如何工作的?

c# - C# 与 F# 中的默认排序

java - 使用 Collections.sort(arrayListName) 按 id 对充满对象的 ArrayList 进行排序

sorting - Prolog - 如何让尾部不为空

python - 仅从 s3 存储桶文件夹中获取文件名