PYTHON

Sort List of Dictionaries by Multiple Keys

Master sorting complex data structures in Python by ordering a list of dictionaries or objects using multiple attributes with `itemgetter` or lambda.

from operator import itemgetter

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

# Sort by 'age' (primary) then 'name' (secondary), both ascending
sorted_by_age_name_asc = sorted(data, key=itemgetter('age', 'name'))
print("Sorted by age then name (ascending):")
for item in sorted_by_age_name_asc:
    print(item)
# Expected:
# {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}
# {'name': 'David', 'age': 25, 'city': 'New York'}
# {'name': 'Alice', 'age': 30, 'city': 'New York'}
# {'name': 'Charlie', 'age': 30, 'city': 'Chicago'}

# Sort by 'city' (primary) then 'age' (secondary), both descending
sorted_by_city_age_desc = sorted(data, key=itemgetter('city', 'age'), reverse=True)
print("
Sorted by city then age (descending):")
for item in sorted_by_city_age_desc:
    print(item)
# Expected:
# {'name': 'David', 'age': 25, 'city': 'New York'}
# {'name': 'Alice', 'age': 30, 'city': 'New York'}
# {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}
# {'name': 'Charlie', 'age': 30, 'city': 'Chicago'}

# For mixed ascending/descending, use a lambda:
# Sort by 'city' ascending, then 'age' descending
sorted_mixed = sorted(data, key=lambda x: (x['city'], -x['age']))
print("
Sorted by city (asc) then age (desc):")
for item in sorted_mixed:
    print(item)
# Expected:
# {'name': 'Charlie', 'age': 30, 'city': 'Chicago'}
# {'name': 'Alice', 'age': 30, 'city': 'New York'}
# {'name': 'David', 'age': 25, 'city': 'New York'}
# {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}
How it works: This snippet shows how to sort a list of dictionaries by multiple keys using `sorted()`. The `key` argument takes a function that extracts a comparison key from each element. `operator.itemgetter` is convenient for extracting multiple dictionary keys as a tuple, allowing for multi-level sorting (primary, then secondary, etc.). For mixed ascending and descending orders, a `lambda` function is more flexible, allowing you to manipulate the sorting values (e.g., negating numbers 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