【问题标题】:Sort a dictionary by value (decreasing) and then by key (increasing)按值(递减)然后按键(递增)对字典进行排序
【发布时间】: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


    【解决方案1】:

    您可以利用 Python 的排序稳定这一事实,分两步执行排序。首先按最不重要的分量值排序,然后按最重要的分量值排序:

    dictionary = {('shall', 'prove'): 1, ('shall', 'not'): 1,
                  ('shall', 'go'): 1, ('shall', 'fight'): 7, 
                  ('shall', 'defend'): 1, ('shall', 'never'): 1}
    
    byKeyAscending = sorted(dictionary.items()) 
    sortedDict = sorted(byKeyAscending,key=lambda kv:kv[1],reverse=True)
    
    [(('shall', 'fight'), 7), (('shall', 'defend'), 1), 
     (('shall', 'go'), 1), (('shall', 'never'), 1), 
     (('shall', 'not'), 1), (('shall', 'prove'), 1)]
    

    对于您的特定示例,假设值是数字,您可以使用否定来反转顺序并在一个步骤中执行排序:

    sortedDict=sorted(dictionary.items(),key=lambda kv:(-kv[1],kv[0]))
    

    【讨论】:

      【解决方案2】:

      按降序对值进行排序与​​按升序对负值进行排序相同。排序可以通过创建一个自定义元组来完成

      sorted(dictionary.items(), key=lambda x:(-x[1],) + x[0])
      [(('shall', 'fight'), 7), (('shall', 'defend'), 1), (('shall', 'go'), 1), (('shall', 'never'), 1), (('shall', 'not'), 1), (('shall', 'prove'), 1)]
      

      【讨论】:

        猜你喜欢
        • 2012-04-12
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 2015-04-06
        相关资源
        最近更新 更多