How to Sort a List of Dictionaries by Key in Python
Sort a list of dictionaries by various keys (grade, age, name) using lambda, itemgetter, and extract unique sorted names into a set.
Python code
32 linesfrom operator import itemgetter
# Sample data: a list of dictionaries representing students
students = [
{"name": "Alice", "grade": 88, "age": 23},
{"name": "Bob", "grade": 95, "age": 22},
{"name": "Charlie", "grade": 78, "age": 24},
{"name": "Diana", "grade": 92, "age": 21}
]
# Sort by grade (descending) using lambda
by_grade_desc = sorted(students, key=lambda s: s["grade"], reverse=True)
# Sort by age (ascending) using itemgetter
by_age_asc = sorted(students, key=itemgetter("age"))
# Sort by name (alphabetic) and extract just names into a set
names_sorted = sorted(s["name"] for s in students)
unique_names = set(names_sorted)
if __name__ == "__main__":
print("Sorted by grade (high to low):")
for s in by_grade_desc:
print(f" {s['name']}: {s['grade']}")
print("\nSorted by age (low to high):")
for s in by_age_asc:
print(f" {s['name']}: {s['age']}")
print("\nUnique names, sorted:")
for name in unique_names:
print(f" {name}")
Output
Sorted by grade (high to low):
Bob: 95
Diana: 92
Alice: 88
Charlie: 78
Sorted by age (low to high):
Diana: 21
Bob: 22
Alice: 23
Charlie: 24
Unique names, sorted:
Alice
Bob
Charlie
Diana
How it works
The sorted() function returns a new list, leaving the original students list untouched. Using key=lambda s: s["grade"] extracts a specific value from each dictionary for comparison. itemgetter("age") from the operator module is a faster, more readable alternative for simple key lookups. The generator expression s["name"] for s in students collects names, which sorted() orders alphabetically, and set() removes duplicates while preserving uniqueness.
Common mistakes
- Forgetting `reverse=True` when you want descending order — default is ascending.
- Using `.sort()` on the original list when you need to keep the original data unchanged.
- Assuming keys exist without checking — a missing key raises `KeyError` during sorting.
Variations
- Use `key=lambda s: (-s["grade"], s["name"])` for multi-level sorting (grade desc, then name asc).
- For data with many dictionary keys, `itemgetter("age", "grade")` can sort by multiple fields at once.
Real-world use cases
- Ranking user profiles by score in a leaderboard API before returning results.
- Sorting product records by price or popularity in an e-commerce catalog.
- Deduplicating and alphabetizing a list of employee names pulled from a database.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.