PYTHON
Advanced Sorting of Dictionaries by Multiple Keys
Master sorting a list of dictionaries in Python by one or more keys, including handling reverse order, essential for displaying structured data in web applications.
# Example data: a list of user records
users = [
{"id": 101, "name": "Alice", "age": 30, "status": "active"},
{"id": 103, "name": "Bob", "age": 25, "status": "inactive"},
{"id": 102, "name": "Charlie", "age": 35, "status": "active"},
{"id": 105, "name": "Alice", "age": 28, "status": "active"},
{"id": 104, "name": "David", "age": 25, "status": "active"},
]
print("Original Users:")
for user in users:
print(user)
# Sort by 'age' in ascending order
# (using a lambda function for the key)
sorted_by_age = sorted(users, key=lambda user: user["age"])
print("
Sorted by Age (Ascending):")
for user in sorted_by_age:
print(user)
# Sort by 'status' (ascending) then by 'name' (ascending)
# The order of tuples in the key function determines sort priority
sorted_by_status_then_name = sorted(
users, key=lambda user: (user["status"], user["name"])
)
print("
Sorted by Status then Name (Ascending):")
for user in sorted_by_status_then_name:
print(user)
# Sort by 'age' (descending)
sorted_by_age_desc = sorted(users, key=lambda user: user["age"], reverse=True)
print("
Sorted by Age (Descending):")
for user in sorted_by_age_desc:
print(user)
How it works: This snippet demonstrates how to sort a list of dictionaries based on one or more keys, a common task in web development for presenting data. It uses the sorted() function with a lambda expression to define the sorting key. You can sort by a single key (e.g., age), by multiple keys (e.g., status then name), and specify reverse=True for descending order. This provides powerful and flexible sorting capabilities for displaying dynamic content.