【发布时间】:2022-01-10 18:41:46
【问题描述】:
我有一本字典,我希望先按值按降序排序,然后按键按升序(字母顺序)排序
我的输入看起来像
{('shall', 'prove'): 1, ('shall', 'not'): 1, ('shall', 'go'): 1, ('shall', 'fight'): 7, ('shall', 'defend'): 1, ('shall', 'never'): 1}
我希望我的输出看起来像
[(('shall', 'fight'), 7), (('shall', 'defend'), 1), (('shall', 'go'), 1), (('shall', 'never'), 1), (('shall', 'not'), 1) (('shall', 'prove'), 1), ]
我试过了
def sort_dict(dictionary):
unsorted_list = list(dictionary.items())
sorted_list = sorted(unsorted_list, key=operator.itemgetter(1), reverse=True)
return sorted_list
按值递减排序,但我不确定如何同时按递增键排序。 如果我需要提供任何进一步的信息,请告诉我。 谢谢!
【问题讨论】:
标签: python list sorting dictionary tuples