Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting list of dict by multiple keys in dict

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)

like image 884
mohammed wazeem Avatar asked Nov 23 '25 21:11

mohammed wazeem


1 Answers

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'}
]
like image 56
Nick Avatar answered Nov 26 '25 12:11

Nick