Sort a List of Dictionaries by Key in Python

Uses a lambda function with sorted() to order a list of dictionaries by a specified key, like price.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 12 views 0 copies

Python code

12 lines
Python 3.9+
def get_items():
    return [
        {"name": "apple", "price": 3},
        {"name": "banana", "price": 1},
        {"name": "cherry", "price": 2},
    ]

if __name__ == "__main__":
    items = get_items()
    sorted_items = sorted(items, key=lambda item: item["price"])
    for item in sorted_items:
        print(f"{item['name']}: ${item['price']}")

Output

stdout
banana: $1
cherry: $2
apple: $3

How it works

The sorted() function takes an iterable and returns a new sorted list. The key parameter specifies a function that extracts a comparison key from each element — here a lambda that returns the 'price' value. Sorting is stable, so equal-price items retain their original order. The lambda is concise and avoids writing a separate function.

Common mistakes

  • Including the lambda without the `key=` keyword — you must pass it as `key=lambda...`
  • Trying to sort a list of dicts without a key, which raises a TypeError
  • Mutating the original list when you want a new sorted copy — use sorted() instead of list.sort()

Variations

  1. Use `items.sort(key=lambda item: item['price'])` to sort in-place
  2. Reverse order with `sorted(items, key=lambda item: item['price'], reverse=True)`

Real-world use cases

  • Ordering a list of product records by price for an e-commerce listing.
  • Sorting API response items by timestamp before displaying them in a dashboard.
  • Ranking user scores in a leaderboard by a numeric attribute from a data export.

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.