The main idea is copied from here.
from collections import OrderedDict
diction = {"Book":(1, 2), "Armchair":(2, 2), "Lamp":(1, 3)}
diction_list = list(diction.items())
diction = OrderedDict(sorted(diction_list, key=lambda x: (-x[1][1], x[0])))
print(diction)
OrderedDict([('Lamp', (1, 3)), ('Armchair', (2, 2)), ('Book', (1, 2))])
Here is where the magic is happening:
sorted(diction_list, key=lambda x: (-x[1][1], x[0]))
sorted
sorts stuff for you. It is very good at it. If you use the key
parameter with sort, you can give it a function to be used on each item to be sorted.
In this case, we are giving at a lambda
that returns the negative value from the tuples -x[1][1]
(this is the second value in the tuple) and the key x[0]
. The negative sign makes it sort in reverse. Of course, this would not work with non-numeric values.
The OrderedDict
thing is not strictly necessary. Python keeps dict in order after version 3.6 I think (or was it 3.7?). OrderedDicts are always kept in the same order, so it is there that so our dict stays ordered independent of the Python version.
For a better way of doing this see the Sorting HOW TO in Python Documentation.