How to Use Lambda Sorting Keys in Python
Learn to sort lists of dictionaries using lambda functions as key arguments in Python's sorted() method.
Python code
25 lines# Demonstrate lambda as a sorting key function
students = [
{"name": "Alice", "grade": 88},
{"name": "Bob", "grade": 92},
{"name": "Charlie", "grade": 75},
{"name": "Diana", "grade": 95}
]
# Sort by grade (ascending) using a lambda key
sorted_by_grade = sorted(students, key=lambda student: student["grade"])
print("Sorted by grade (ascending):")
for student in sorted_by_grade:
print(f" {student['name']}: {student['grade']}")
# Sort by name (descending) using a lambda key
sorted_by_name = sorted(students, key=lambda student: student["name"], reverse=True)
print("\nSorted by name (descending):")
for student in sorted_by_name:
print(f" {student['name']}: {student['grade']}")
if __name__ == "__main__":
print("\nTotal students:", len(students))
Output
Sorted by grade (ascending):
Charlie: 75
Alice: 88
Bob: 92
Diana: 95
Sorted by name (descending):
Diana: 95
Charlie: 75
Bob: 92
Alice: 88
Total students: 4
How it works
The sorted() function takes a key parameter that specifies a function to extract a comparison key from each element. Here, a lambda function lambda student: student["grade"] is used to return the grade value for sorting. For descending order, set reverse=True. Lambda functions are concise anonymous functions that are perfect for simple key extraction. They do not require a def statement and can be defined inline, making them ideal for sorting and other functional programming patterns.
Common mistakes
- Forgetting to use the `key` parameter and sorting by the dictionary itself, which raises a TypeError.
- Not understanding that `reverse=True` changes order but does not change the key function.
- Using a lambda that returns a list or dict directly, which causes comparison errors.
Variations
- Use `operator.itemgetter` as an alternative to lambda for dictionary key access.
- Sort multiple keys by returning a tuple `(key1, key2)` from the lambda.
Real-world use cases
- Sorting API response data by a timestamp or priority field before rendering a dashboard.
- Ordering database query results by a computed score (e.g., weighted rating) in memory.
- Sorting a list of user records by last name or email address for display in a UI.
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.