I have a list of dictionary
data = [{'name' : 'messi', 'place': 'barcelona'}, {'name': 'salah', 'place': 'liverpool'},
{'name': 'neymar', 'place': 'paris'}, {'name': 'suarez', 'place': 'barcelona'}]
I want to sort this list of dict by multiple keys place in ascending and name in descending order
I know how to sort the list of dict with multiple fields, both in ascending
sorted(data, key=lambda x: (x['name'], x['place']))
But I am not sure how to achieve one field in ascending and another in descending( both are str type)
You need to sort twice, first by name in descending order, and then by place in ascending order, relying on the fact that python sort is stable, so that if two entries have the same place value, their ordering will be preserved in the second sort (so name will remain sorted descending):
sorted(sorted(data, key=lambda x: x['name'], reverse=True), key=lambda x: x['place'])
Output
[
{'name': 'suarez', 'place': 'barcelona'},
{'name': 'messi', 'place': 'barcelona'},
{'name': 'salah', 'place': 'liverpool'},
{'name': 'neymar', 'place': 'paris'}
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With