How do I sort a list of dictionaries by a key in Python?
Short answer
Use sorted with a key function that pulls out the field to sort on, usually a lambda or itemgetter. Add reverse for descending order, and provide a fallback for missing keys.
The short version
Use sorted with a key function that returns the field you want to sort on. A lambda is the usual choice, or operator.itemgetter for a touch more speed. Add reverse=True for descending order. Handle missing keys deliberately, or the sort will raise.
The basic sort
people = [
{"name": "Ana", "age": 30},
{"name": "Bo", "age": 25},
]
by_age = sorted(people, key=lambda d: d["age"])
print([d["name"] for d in by_age]) # ['Bo', 'Ana']
The key function is called once per item, and Python sorts by whatever it returns, here the age.
Descending order
sorted(people, key=lambda d: d["age"], reverse=True)
Sorting by more than one field
Return a tuple from the key function to sort by several fields, with earlier ones taking priority.
sorted(people, key=lambda d: (d["age"], d["name"]))
This orders by age, then by name where ages tie. It mirrors how spreadsheet sorting handles multiple levels.
itemgetter as an alternative
operator.itemgetter does the same job as a simple lambda and is marginally faster.
from operator import itemgetter
sorted(people, key=itemgetter("age"))
Handling missing keys
If some dictionaries lack the key, d["age"] raises KeyError. Use .get with a default so every item yields a comparable value.
sorted(people, key=lambda d: d.get("age", 0))
Choose a default that sorts sensibly for your data, for example 0 or float("inf") depending on whether missing should sort first or last.
sorted versus sort
sorted returns a new list and leaves the original alone. The list method people.sort(key=...) sorts in place and returns None. Use sorted when you want to keep the original order too, and .sort() when you are happy to reorder the list itself. Do not write people = people.sort(...), because that assigns None.