PYTHON
Sorting Lists of Dictionaries by Multiple Keys
Discover how to sort a list of dictionaries in Python by multiple specified keys, handling both ascending and descending orders, a common task for presenting structured data in web apps.
users_data = [
{"name": "Alice", "age": 30, "city": "New York"},
{"name": "Bob", "age": 25, "city": "Los Angeles"},
{"name": "Alice", "age": 28, "city": "Chicago"},
{"name": "Charlie", "age": 35, "city": "New York"},
]
# Sort primarily by 'name' (ascending), then by 'age' (ascending)
sorted_users_name_age_asc = sorted(users_data, key=lambda user: (user['name'], user['age']))
# Sort primarily by 'city' (ascending), then by 'age' (descending)
sorted_users_city_age_desc = sorted(
users_data,
key=lambda user: (user['city'], -user['age']) # -user['age'] for descending numerical sort
)
# print("Sorted by name (asc), then age (asc):")
# for user in sorted_users_name_age_asc:
# print(user)
# print("
Sorted by city (asc), then age (desc):")
# for user in sorted_users_city_age_desc:
# print(user)
How it works: This snippet illustrates how to sort a list of dictionaries using Python's `sorted()` function with a custom `key` argument. By providing a lambda function that returns a tuple of values (e.g., `(user['name'], user['age'])`), you can define primary and secondary sorting criteria. For descending numerical sorts, you can negate the value (e.g., `-user['age']`) within the tuple. This is crucial for presenting ordered data, like search results or user lists, in web interfaces.