![]() |
VOOZH | about |
We are given a list of dictionaries where each dictionary contains various keys and our task is to sort the list by multiple keys. Sorting can be done using different methods such as using the sorted() function, a list of tuples, itemgetter() from the operator module. For example, if we have the following list of dictionaries: d= [ {'name': 'Aryan', 'age': 25, 'score': 90}, {'name': 'Harsh', 'age': 22, 'score': 95}, {'name': 'Kunal', 'age': 25, 'score': 85}]. The output after sorting by age and score will be: [ {'name': 'Harsh', 'age': 22, 'score': 95}, {'name': 'Kunal', 'age': 25, 'score': 85}, {'name': 'Aryan', 'age': 25, 'score': 90}]
sorted() function is a built-in Python function that sorts any iterable and returns a new sorted list. It can be used with a custom sorting key to sort dictionaries based on multiple keys. By passing a lambda function we can sort the list of dictionaries based on multiple keys such as age and score.
[{'name': 'Harsh', 'age': 22, 'score': 95}, {'name': 'Kunal', 'age': 25, 'score': 85}, {'name': 'Aryan', 'age': 25, 'score': 90}]
Explanation: lambda x: (x['age'], x['score']) defines the sorting criteria where the list is first sorted by age and then by score and sorted() returns a new list leaving the original list unchanged.
In this method we create a list of tuples where each tuple contains the values of the keys we want to sort by followed by the original dictionary. This list of tuples is then sorted based on the values of the keys and the sorted dictionaries are extracted from the tuples.
[{'name': 'Harsh', 'age': 22, 'score': 95}, {'name': 'Kunal', 'age': 25, 'score': 85}, {'name': 'Aryan', 'age': 25, 'score': 90}]
Explanation:
In this method we use itemgetter from the operator module to sort the list of dictionaries by multiple keys such as age and score.
[{'name': 'Harsh', 'age': 22, 'score': 95}, {'name': 'Kunal', 'age': 25, 'score': 85}, {'name': 'Aryan', 'age': 25, 'score': 90}]