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

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)]

Leave a Comment