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.

Easy Python 3.6+ Aug 9, 2026 Functions & basics 15 views 0 copies

Python code

25 lines
Python 3.6+
# 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

stdout
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

  1. Use `operator.itemgetter` as an alternative to lambda for dictionary key access.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.