Hello,

A few days ago I faced the need to sort a list of tuples. Maybe the data structure is not so good and we should refactor them to use a list of dictionaries, but it is used by a lot of functions and methods.

This list of tuples contains pairs of an integer and a string, and it's need to be sorted by the first elements ascending and then by the second elements descending, so, I decided to use the following approach:

d = ((1, 'aaa'), (1, 'aab'), (1, 'aaac'))
d_dict = {j: n for n, j in enumerate(sorted([i[1] for i in d]))}
dd = sorted(d, key=lambda x: (x[0], -d_dict[x[1]]))
print(dd)
Python: use an additional dict for sorting landmark

Don Graham from Redlands, CA, USA - God bless it!, CC BY-SA 2.0, via Wikimedia Commons