How to Sort a List of Dictionaries by Key with a Lambda in Python
Sort a list of dictionaries ascending or descending by one of their keys using sorted() with a lambda as the key function — a beginner-friendly pattern.
Python code
19 linesdef get_students():
return [
{"name": "alice", "score": 85},
{"name": "bob", "score": 92},
{"name": "carol", "score": 78},
{"name": "dave", "score": 92},
]
students = get_students()
sorted_by_score = sorted(students, key=lambda s: s["score"])
print("Sorted by score (ascending):")
for student in sorted_by_score:
print(f" {student['name']} - {student['score']}")
sorted_by_score_desc = sorted(students, key=lambda s: s["score"], reverse=True)
print("\nSorted by score (descending):")
for student in sorted_by_score_desc:
print(f" {student['name']} - {student['score']}")
Output
Sorted by score (ascending):
carol - 78
alice - 85
bob - 92
dave - 92
Sorted by score (descending):
bob - 92
dave - 92
alice - 85
carol - 78
How it works
The sorted() function takes an iterable and returns a new sorted list. The key parameter receives a function that is called on each element to extract the value to sort by. A lambda lambda s: s["score"] is a concise way to pull out the score key from each dictionary. Setting reverse=True reverses the order, giving descending output. Because sorted is stable, students with equal scores keep their original relative order (bob before dave in the descending example).
Common mistakes
- Forgetting to specify the key, which would sort by the dictionary's hash, raising an error.
- Using `students.sort()` instead of `sorted()` to avoid modifying the original list.
- Confusing ascending vs descending — remember `reverse=True` for descending.
Variations
- Sort by multiple keys: `sorted(students, key=lambda s: (s["score"], s["name"]))`.
- Sort in place with `students.sort(key=lambda s: s["score"])`.
Real-world use cases
- Sorting a list of user records from a database by registration date before displaying a leaderboard.
- Ordering log entries by timestamp when processing a batch of events.
- Ranking products by price or rating in an e-commerce API response.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.