← Back to all snippets
PYTHON

Sort Lists of Dictionaries by Multiple Keys

Master sorting complex Python lists containing dictionaries by single or multiple keys, essential for ordering data fetched from APIs or databases in web development.

from operator import itemgetter

users = [
    {'name': 'Alice', 'age': 30, 'city': 'New York'},
    {'name': 'Bob', 'age': 25, 'city': 'London'},
    {'name': 'Charlie', 'age': 30, 'city': 'New York'},
    {'name': 'David', 'age': 35, 'city': 'Paris'},
    {'name': 'Eve', 'age': 25, 'city': 'London'},
]

# Sort by a single key (e.g., 'age')
sorted_by_age = sorted(users, key=itemgetter('age'))
print(f"Sorted by age:
{sorted_by_age}")

# Sort by multiple keys (e.g., 'city' then 'age')
sorted_by_city_age = sorted(users, key=itemgetter('city', 'age'))
print(f"
Sorted by city then age:
{sorted_by_city_age}")

# Sort by a single key in descending order
sorted_by_age_desc = sorted(users, key=itemgetter('age'), reverse=True)
print(f"
Sorted by age (descending):
{sorted_by_age_desc}")

# Sort using a lambda function for more complex logic
# Sort by name length
sorted_by_name_len = sorted(users, key=lambda user: len(user['name']))
print(f"
Sorted by name length:
{sorted_by_name_len}")
How it works: Sorting a list of dictionaries is a very common requirement in web development when dealing with structured data, such as records retrieved from a database or a JSON API response. This snippet demonstrates how to use `sorted()` with the `key` argument. `itemgetter` from the `operator` module is highly efficient for sorting by one or multiple dictionary keys. For more complex sorting logic, a `lambda` function can be used to define a custom key extraction, allowing flexible ordering based on derived values or multiple criteria.

Need help integrating this into your project?

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

Hire DigitalCodeLabs