Sort List of Dictionaries by Multiple Keys - Python
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}]
Using sorted() Function
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.
data = [
{'name': 'Aryan', 'age': 25, 'score': 90},
{'name': 'Harsh', 'age': 22, 'score': 95},
{'name': 'Kunal', 'age': 25, 'score': 85}
]
a = sorted(data, key=lambda x: (x['age'], x['score']))
print(a)
Output
[{'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.
Using List of Tuples
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.
data = [
{'name': 'Aryan', 'age': 25, 'score': 90},
{'name': 'Harsh', 'age': 22, 'score': 95},
{'name': 'Kunal', 'age': 25, 'score': 85}
]
t = sorted([(x['age'], x['score'], x) for x in data])
d = [x[2] for x in t]
print(d)
Output
[{'name': 'Harsh', 'age': 22, 'score': 95}, {'name': 'Kunal', 'age': 25, 'score': 85}, {'name': 'Aryan', 'age': 25, 'score': 90}]
Explanation:
- [(x['age'], x['score'], x) for x in data] creates the list of tuples with age, score and the dictionary x.
- list is sorted by the first two elements in the tuple and the original dictionary is retrieved with [x[2] for x in t].
Using itemgetter() Method
In this method we use itemgetter from the operator module to sort the list of dictionaries by multiple keys such as age and score.
from operator import itemgetter
data = [
{'name': 'Aryan', 'age': 25, 'score': 90},
{'name': 'Harsh', 'age': 22, 'score': 95},
{'name': 'Kunal', 'age': 25, 'score': 85}
]
d = sorted(data, key=itemgetter('age', 'score'))
print(d)
Output
[{'name': 'Harsh', 'age': 22, 'score': 95}, {'name': 'Kunal', 'age': 25, 'score': 85}, {'name': 'Aryan', 'age': 25, 'score': 90}]