PYTHON

Sort a List of Dictionaries by a Nested Key

Learn to sort a list of Python dictionaries based on a value located within a nested dictionary or complex structure, a common task in web development for ordering API responses.

data = [
    {"id": 1, "details": {"name": "Alice", "age": 30}},
    {"id": 2, "details": {"name": "Charlie", "age": 25}},
    {"id": 3, "details": {"name": "Bob", "age": 35}}
]

# Sort by 'age' within 'details' in ascending order
sorted_by_age = sorted(data, key=lambda x: x['details']['age'])
print("Sorted by Age (Ascending):", sorted_by_age)

# Sort by 'name' within 'details' in descending order
sorted_by_name_desc = sorted(data, key=lambda x: x['details']['name'], reverse=True)
print("Sorted by Name (Descending):", sorted_by_name_desc)
How it works: This snippet demonstrates how to sort a list of dictionaries where the sorting key is nested within another dictionary. It uses the `sorted()` function with a `lambda` expression as the `key` argument, which allows specifying a custom function to extract the comparison key for each element. The `reverse=True` argument sorts in 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