← Back to all snippets
PYTHON

Sort a List of Dictionaries by Multiple Keys

Learn to sort a list of dictionaries in Python by one or more keys, in ascending or descending order, using lambda functions and the sorted() method.

students = [
    {"name": "Alice", "age": 25, "grade": "A"},
    {"name": "Bob", "age": 22, "grade": "B"},
    {"name": "Charlie", "age": 25, "grade": "C"},
    {"name": "David", "age": 23, "grade": "A"}
]

# Sort by 'age' in ascending order
sorted_by_age = sorted(students, key=lambda student: student['age'])
print("Sorted by age (ascending):")
for s in sorted_by_age: print(s)

# Sort by 'age' (ascending) then by 'grade' (descending)
sorted_by_age_grade = sorted(students, key=lambda student: (student['age'], student['grade']), reverse=False)
print("
Sorted by age (asc) then grade (asc):")
for s in sorted_by_age_grade: print(s)

# To achieve 'grade' descending while 'age' is ascending, a custom key logic is needed, 
# or sort multiple times (less efficient for large lists).
# For age (asc), grade (desc), we can negate numerical values or reverse string order if possible.
# Here's an example for age (asc) and then grade (desc) by creating a sortable inverse:
# Assume grades can be mapped to a numerical value where 'A' is highest.
grade_mapping = {'A': 3, 'B': 2, 'C': 1, 'D': 0}
sorted_complex = sorted(students, key=lambda s: (s['age'], -grade_mapping[s['grade']]))
print("
Sorted by age (asc) then grade (desc):")
for s in sorted_complex: print(s)

# Expected output for age (asc) then grade (desc):
# Sorted by age (asc) then grade (desc):
# {'name': 'Bob', 'age': 22, 'grade': 'B'}
# {'name': 'David', 'age': 23, 'grade': 'A'}
# {'name': 'Alice', 'age': 25, 'grade': 'A'}
# {'name': 'Charlie', 'age': 25, 'grade': 'C'}
How it works: This snippet demonstrates how to sort a list of dictionaries in Python using the `sorted()` function with a `lambda` key. For single-key sorting, the `lambda` extracts the value of the desired key. For multi-key sorting, the `lambda` returns a tuple of key values. Python sorts tuples lexicographically, meaning it compares the first elements, then the second if the first are equal, and so on. To achieve mixed ascending/descending order on different keys (e.g., age ascending, grade descending), you can negate numerical keys or implement custom logic within the `lambda` to create sortable inverse values.

Need help integrating this into your project?

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

Hire DigitalCodeLabs