【问题标题】:Sorting Dictionary first by value , then by keys in python 3 [duplicate]首先按值排序字典,然后按python 3中的键[重复]
【发布时间】:2020-09-14 07:34:57
【问题描述】:

我按值对 Dict 进行排序,但当值相等时,键应按字母顺序排序。 我希望我的输出按它们的值降序排序,然后按它们的键(按字母顺序)升序(A-Z)

【问题讨论】:

  • 请显示一些示例数据,因此您的键和值的类型是已知的。另外,你期望什么输出?打印或项目列表...?

标签: python python-3.x sorting dictionary key-value


【解决方案1】:
my_dictionary = dict({'ca': 'a', 'cb': 'c', 'n': 'b', 'd': 'z', 'f': 'a'})
l=my_dictionary.items() # get a list of (k, v)
l.sort(key=lambda x: x[0],reverse=False) # sort by key in ascending order
l.sort(key=lambda x: x[1],reverse=True) # sort by value in descending order
ordered_keys=[t[0] for t in l] # get an ordered list of the keys

此代码为您提供了一个排序的键列表,您可以使用这些键以您想要的顺序访问值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-18
    • 2023-03-04
    • 1970-01-01
    • 2011-12-06
    • 2016-11-03
    • 2019-06-26
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多