【问题标题】:How to sort python dictionary by values in descending order. If two values are same then sort items lexicographically? [duplicate]如何按值按降序对python字典进行排序。如果两个值相同,那么按字典顺序对项目进行排序? [复制]
【发布时间】:2019-08-10 21:56:50
【问题描述】:
dictionary={'b': 5, 'a': 2, 'k': 5}

正确的输出应该是:dictionary={'b': 5, 'k': 5, 'a': 2}

使用了以下方法:

sorted(dictionary.items(), key=itemgetter(1), reverse=True)

但输出为{'k': 5, 'b': 5, 'a': 2}

edit1:我正在使用 Python 3

【问题讨论】:

  • 请注意,根据您的python版本,dicts 未排序,您可能需要使用docs.python.org/3/library/…
  • 您使用的是哪个 Python 版本?

标签: python


【解决方案1】:

您的 python 版本可能不会保持您输入键值对的顺序。在这种情况下,您可以使用collections.OrderedDict

from operator import itemgetter
from collections import OrderedDict

dictionary={'b': 5, 'a': 2, 'k': 5}

s = OrderedDict(sorted(dictionary.items(), key=itemgetter(1), reverse=True))
print(s)
# OrderedDict([('b', 5), ('k', 5), ('a', 2)])

如果你的 python 版本是 starting from python 3.7 this is considered 成为语言规范的一部分。

所以从 python 3.7 开始,您的代码将不需要 OrderedDict,您可以使用常规的 dict

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 2012-08-09
    • 2019-09-09
    • 1970-01-01
    • 2011-02-09
    • 2010-10-11
    相关资源
    最近更新 更多