We are given a list of dictionaries where each dictionary contains multiple key-value pairs and our task is to sort this list based on the value of a specific key. For example, Given the list: students = [{'name': 'David', 'score': 85}, {'name': 'Sophia', 'score': 92}, {'name': 'Ethan', 'score': 78}], sorting by the score key will result in: [{'name': 'Ethan', 'score': 78}, {'name': 'David', 'score': 85}, {'name': 'Sophia', 'score': 92}].
Using sorted() with lambda
sorted() function along with a lambda function is used to sort the list of dictionaries by the desired key and this is the most efficient approach as it directly sorts the list in one line without requiring additional data structures.
li = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 20}]
# sorting using lambda
res = sorted(li, key=lambda x: x['age'])
print(str(res))
Output
[{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
Explanation: sorted() is used to sort the list and lambda x: x['age'] is used to extract the value of the 'age'.
Using itemgetter() from operator module
itemgetter() function from the operator module is used to sort a list of dictionaries by a specific key.
from operator import itemgetter
li = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 20}]
# sorting using itemgetter
res = sorted(li, key=itemgetter('age'))
print(str(res))
Output
[{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
Explanation: itemgetter('age') returns a callable that fetches the 'age' key from each dictionary for sorting.
Using Loops
This method uses a loop to compare and swap elements based on a specified key.
li = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 20}]
# Bubble sort logic
for i in range(len(li)):
for j in range(len(li) - i - 1):
if li[j]['age'] > li[j + 1]['age']:
li[j], li[j + 1] = li[j + 1], li[j]
print(li)
Output
[{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
Explanation: Outer loop runs for each element in the list, inner loop compares adjacent elements by their age key and swaps them if they are out of order thus sorting the list based on age.