先按值排序字典,然后按 python 中的键排序 3

Sorting Dictionary first by value , then by keys in python 3

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

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

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