![]() |
VOOZH | about |
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}].
sorted() with lambdasorted() 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.
[{'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'.
itemgetter() from operator moduleitemgetter() function from the operator module is used to sort a list of dictionaries by a specific key.
[{'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.
This method uses a loop to compare and swap elements based on a specified key.
[{'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.