PYTHON
Sort List of Dictionaries by Multiple Keys in Python
Learn to sort a list of Python dictionaries based on multiple specified keys, handling primary and secondary sort orders for complex data arrangements.
users = [
{"name": "Alice", "age": 30, "city": "New York"},
{"name": "Bob", "age": 25, "city": "London"},
{"name": "Charlie", "age": 30, "city": "Paris"},
{"name": "David", "age": 25, "city": "New York"},
{"name": "Eve", "age": 35, "city": "London"},
]
print("Original Users:")
for user in users:
print(user)
# Sort primarily by 'age' (ascending) and secondarily by 'name' (ascending)
sorted_users_age_name = sorted(users, key=lambda x: (x["age"], x["name"]))
print("
Sorted by Age (asc), then Name (asc):")
for user in sorted_users_age_name:
print(user)
# Sort primarily by 'city' (ascending) and secondarily by 'age' (descending)
# For descending order, multiply the value by -1 (for numbers) or reverse sort the string
sorted_users_city_age_desc = sorted(users, key=lambda x: (x["city"], -x["age"]))
print("
Sorted by City (asc), then Age (desc):")
for user in sorted_users_city_age_desc:
print(user)
# To sort strings in descending order, you might need a different approach for complex cases
# or simply reverse the final list if only one key is descending.
# For a purely string key descending sort:
sorted_users_name_desc = sorted(users, key=lambda x: x["name"], reverse=True)
print("
Sorted by Name (desc):")
for user in sorted_users_name_desc:
print(user)
How it works: This snippet demonstrates how to sort a list of dictionaries by multiple keys in Python. The `sorted()` function (or `list.sort()`) accepts a `key` argument, which can be a `lambda` function returning a tuple. When a tuple is returned, Python sorts based on the first element, then the second, and so on. For descending order of numeric values, multiplying by -1 is a common trick. This technique is invaluable for arranging complex datasets for display or processing based on specific hierarchical criteria.