← Back to all snippets
PYTHON

Sorting a List of Dictionaries by Key

Learn how to sort a list of dictionaries in Python based on the values of a specific key, using `lambda` functions for flexible and custom sorting orders, including multi-level sorting.

users = [
    {'name': 'Alice', 'age': 30, 'city': 'New York'},
    {'name': 'Bob', 'age': 24, 'city': 'Los Angeles'},
    {'name': 'Charlie', 'age': 30, 'city': 'Chicago'},
    {'name': 'David', 'age': 24, 'city': 'Miami'}
]

# Sort by 'age' (ascending)
sorted_by_age = sorted(users, key=lambda user: user['age'])
print("Sorted by age (asc):")
for user in sorted_by_age:
    print(user)

# Sort by 'age' (descending) then by 'name' (ascending)
sorted_by_age_desc_name_asc = sorted(users, key=lambda user: (user['age'], user['name']), reverse=True)
print("
Sorted by age (desc) then name (asc):")
for user in sorted_by_age_desc_name_asc:
    print(user)
How it works: This snippet demonstrates how to sort a list of dictionaries in Python using the `sorted()` function or the list's `sort()` method. The `key` argument accepts a function that extracts a comparison key from each element. A `lambda` function is commonly used here to specify which dictionary key (e.g., `'age'`) should be used for sorting. For multi-level sorting, you can provide a tuple of keys to the `lambda` function, and Python will sort by the first key, then the second, and so on. The `reverse=True` argument can be used for descending order.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs