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.
Python code
12 linesdef 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
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
- Use `items.sort(key=lambda item: item['price'])` to sort in-place
- 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
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.