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.

Easy Python 3.8+ Aug 9, 2026 Functions & basics 13 views 0 copies

Python code

19 lines
Python 3.8+
def 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

stdout
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

  1. Sort by multiple keys: `sorted(students, key=lambda s: (s["score"], s["name"]))`.
  2. 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

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.