【发布时间】:2020-09-14 07:34:57
【问题描述】:
我按值对 Dict 进行排序,但当值相等时,键应按字母顺序排序。 我希望我的输出按它们的值降序排序,然后按它们的键(按字母顺序)升序(A-Z)
【问题讨论】:
-
请显示一些示例数据,因此您的键和值的类型是已知的。另外,你期望什么输出?打印或项目列表...?
标签: python python-3.x sorting dictionary key-value
我按值对 Dict 进行排序,但当值相等时,键应按字母顺序排序。 我希望我的输出按它们的值降序排序,然后按它们的键(按字母顺序)升序(A-Z)
【问题讨论】:
标签: python python-3.x sorting dictionary key-value
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
此代码为您提供了一个排序的键列表,您可以使用这些键以您想要的顺序访问值
【讨论】: