PYTHON
Sorting Complex Data (List of Dictionaries) by Multiple Keys
Sort a list of dictionaries or custom objects by one or more keys, including nested keys, using `sort()` or `sorted()` with `lambda` or `itemgetter` for flexible ordering.
from operator import itemgetter
users = [
{"name": "Alice", "age": 30, "score": 95},
{"name": "Bob", "age": 25, "score": 88},
{"name": "Charlie", "age": 30, "score": 92},
{"name": "David", "age": 25, "score": 90}
]
# Sort by a single key (age)
sorted_by_age = sorted(users, key=itemgetter('age'))
# Output:
# [{'name': 'Bob', 'age': 25, 'score': 88}, {'name': 'David', 'age': 25, 'score': 90}, {'name': 'Alice', 'age': 30, 'score': 95}, {'name': 'Charlie', 'age': 30, 'score': 92}]
print("Sorted by Age:", sorted_by_age)
# Sort by multiple keys (age then score, both ascending)
sorted_by_age_score = sorted(users, key=itemgetter('age', 'score'))
# Output:
# [{'name': 'Bob', 'age': 25, 'score': 88}, {'name': 'David', 'age': 25, 'score': 90}, {'name': 'Charlie', 'age': 30, 'score': 92}, {'name': 'Alice', 'age': 30, 'score': 95}]
print("Sorted by Age & Score:", sorted_by_age_score)
# Sort by multiple keys with mixed order (age ascending, score descending)
sorted_mixed_order = sorted(users, key=lambda user: (user['age'], -user['score']))
# Output:
# [{'name': 'David', 'age': 25, 'score': 90}, {'name': 'Bob', 'age': 25, 'score': 88}, {'name': 'Alice', 'age': 30, 'score': 95}, {'name': 'Charlie', 'age': 30, 'score': 92}]
print("Sorted by Age (asc), Score (desc):", sorted_mixed_order)
How it works: Sorting lists of dictionaries is a common requirement in web development for presenting data in a specific order. Python's `sorted()` function (or `list.sort()`) allows custom sorting using the `key` argument. This snippet demonstrates how to sort by a single key, by multiple keys (where the secondary key breaks ties in the primary key), and by multiple keys with mixed ascending/descending order. It utilizes both `operator.itemgetter` for conciseness with single or multiple ascending keys, and `lambda` functions for more complex sorting logic like mixed order.