I have a list of dictionaries whose elements must be sorted according to a rather complex criterion. Please consider this typical element:
{
'key1': True, # always boolean
'key2': False, # always boolean
'key3': 23, # always int
'key4': 1613.34, # always float
'key5': 'Some string', # always str
'key6': 'Some other string', # always str
}
Suppose the desired sort order is: key1 ASC, key2 DESC, key3 ASC, key4 DESC, key5 ASC, key6 DESC
.
I know I could do something like that:
my_sorted_list = sorted(my_list, key=lambda my_dict: (
my_dict['key1'],
-my_dict['key2'],
my_dict['key3'],
-my_dict['key4'],
my_dict['key5'],
tuple(-ord(c) for c in my_dict['key6']) # is that really the way of doing it? :-|
))
But that last expression seems very ugly and hacky (and perhaps inefficient) to me. Is there a cleanest way of performing the same classification?