【问题标题】:How to sort the values of a dictionary in descending order and the keys alphabetically如何按降序对字典的值进行排序,并按字母顺序对键进行排序
【发布时间】:2021-12-20 03:25:06
【问题描述】:

我们如何对字典中的值进行降序排序,如果有两个相似的值,按字母顺序对这些值的键进行排序?

像下面的例子:

Input = {'robert':13, 'walter':17, 'andrew':16, 'adrian':16, 'simon':15, 'santiago':15} 
Output = {'walter':17, 'adrian':16, 'andrew':16, 'santiago':15, 'simon':15}

【问题讨论】:

    标签: python sorting dictionary


    【解决方案1】:

    您可以使用sorted 并设置您想要的密钥,如下所示:

    (如果值相等,您首先要在 value 上对 descending 排序,然后在 key 上排序 ascending

    >>> dct = {'robert':13, 'walter':17, 'andrew':16, 'adrian':16, 'simon':15, 'santiago':15}
    
    >>> dict(sorted(dct.items(), key=lambda x: (-x[1],x[0])))
    {'walter': 17,
     'adrian': 16,
     'andrew': 16,
     'santiago': 15,
     'simon': 15,
     'robert': 13}
    

    【讨论】:

      【解决方案2】:

      你可以用这种方式排序字典的值:

      output = dict(sorted(inp.items(), key=lambda item: item[1], reverse=True))
      

      输出:

      {'walter': 17, 'andrew': 16, 'adrian': 16, 'simon': 15, 'santiago': 15,“罗伯特”:13}

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-04-06
        • 2020-03-19
        • 2020-01-22
        • 2020-12-10
        • 2020-11-26
        • 2011-08-29
        • 2018-01-27
        相关资源
        最近更新 更多