Lets assume I've got a following python list(this is only example):
my_list = [{'user': 'Joe', 'score': 14},
{'user': 'Foo', 'score': 12},
{'user': 'May', 'score': 12},
{'user': 'Kat', 'score': 12},
{'user': 'Doe', 'score': 13}]
I need to sort this list in ascending order by score and descending order by a username. Expected sort result:
my_list = [{'user': 'May', 'score': 12},
{'user': 'Kat', 'score': 12},
{'user': 'Foo', 'score': 12},
{'user': 'Doe', 'score': 13},
{'user': 'Joe', 'score': 14}]
So, I could do something like this if I want everything to be in ascending order:
my_list.sort(key=lambda x: (x['score'], x['user']))
For integers it is easy to solve this problem just adding -
in front of it:
my_list.sort(key=lambda x: (-x['score'], x['user']))
Unfortunately, strings can not be negative :-|
I need a generic solution that doesn't involve 'reverse=True'. Lambda function is dynamically generated based on a user config.
Thoughts?