How to Sort a List of Dictionaries by a Key in Python
Sort a list of dictionaries by a specified key field, optionally in descending order, using Python's built-in sorted() function.
Python code
16 linesdef sort_dicts_by_key(data, key, reverse=False):
return sorted(data, key=lambda item: item.get(key), reverse=reverse)
if __name__ == "__main__":
people = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35},
]
sorted_by_age = sort_dicts_by_key(people, "age")
print(sorted_by_age)
sorted_by_name_desc = sort_dicts_by_key(people, "name", reverse=True)
print(sorted_by_name_desc)
Output
[{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Charlie', 'age': 35}]
[{'name': 'Charlie', 'age': 35}, {'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}]
How it works
The sorted() function returns a new list sorted by the key provided. Using a lambda expression with item.get(key) safely accesses the dictionary field even if some dicts might be missing that key, returning None for missing keys. The reverse parameter controls ascending (False, default) or descending (True) order. Since sorted() does not modify the original list, your data remains unchanged.
Common mistakes
- Using `dict.sort()` on the list directly, which doesn't exist — use `sorted()` with a key function instead.
- Not handling missing keys; `item[key]` raises KeyError while `.get(key)` returns None.
- Forgetting to set `reverse=True` for descending order, resulting in ascending order.
- Assuming sorting is in place; `sorted()` returns a new list, so assign the result.
Variations
- Use `itemgetter` from the operator module for better performance on large lists: `sorted(data, key=itemgetter(key))`.
- For in-place sorting, use `data.sort(key=lambda item: item.get(key), reverse=reverse)`.
Real-world use cases
- Sorting user records by registration date or last login before pagination.
- Ordering product inventory by price or stock level for a storefront display.
- Sorting API responses by a timestamp field before rendering a feed or timeline.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.