How to sort a dictionary by value (DESC) then by key (ASC)?

后端 未结 2 1075
無奈伤痛
無奈伤痛 2020-12-04 22:40

Just after discovering the amazing sorted(), I became stuck again.

The problem is I have a dictionary of the form string(key) : integer(value)

相关标签:
2条回答
  • 2020-12-04 23:11

    Something like

    In [1]: d = {'banana': 3, 'orange': 5, 'apple': 5}
    
    In [2]: sorted(d.items(), key=lambda x: (-x[1], x[0]))
    Out[2]: [('apple', 5), ('orange', 5), ('banana', 3)]
    
    0 讨论(0)
  • 2020-12-04 23:21
    • Dictionaries can't be sorted directly, so you need to instead sort the items(), the list of tuples containing key/value pairs.

    • Since you want to sort by the value field, then the key fields, it is necessary to extract those field from the tuple for use as the sort key using operator.itemgetter which gets the specified field.

    • Lastly, to sort descending on one field and descending on another, do two passes, first sorting by the secondary key ascending, and then another pass sorting by the primary key descending. This step relies on Python's sort stability.

    For example:

    import operator
    In [1]: d = {'banana': 3, 'orange': 5, 'apple': 5}
    
    In [2]: fruit = sorted(d.items(), key=operator.itemgetter(0))
    In [3]: sorted(fruit, key=operator.itemgetter(1), reverse=True)
    Out[3]: [('apple', 5), ('orange', 5), ('banana', 3)]
    

    See the Python Sorting-HOWTO guide for more details.

    0 讨论(0)
提交回复
热议问题