Sort a list of dictionaries by a field in Python

Sort records with a key function, combine multiple fields, choose missing-value behavior, and preserve stable ordering.

Best practices
Python programming and application logging

Use sorted(records, key=lambda record: record["age"]) to return records in ascending age order. Add reverse=True for descending order. The key function extracts the value Python should compare.

Sort one field

users = [
    {"name": "Alex", "age": 28},
    {"name": "Blair", "age": 22},
    {"name": "Casey", "age": 35},
]

ascending = sorted(users, key=lambda user: user["age"])
descending = sorted(users, key=lambda user: user["age"], reverse=True)
print([user["age"] for user in ascending])  # [22, 28, 35]

sorted() creates a new list; it does not copy the dictionaries inside it. Use users.sort(key=...) to reorder the existing list in place. That method returns None.

operator.itemgetter provides another concise key function:

from operator import itemgetter

ascending = sorted(users, key=itemgetter("age"))

Choose the form that makes the extraction clear. Any performance difference depends on the workload.

Combine fields

For numeric ages, sort age descending and name ascending with a tuple key:

ordered = sorted(users, key=lambda user: (-user["age"], user["name"]))

Python compares tuple elements in order. Alternatively, exploit stable sorting by sorting the secondary field first and the primary field afterward:

ordered = sorted(users, key=itemgetter("name"))
ordered.sort(key=itemgetter("age"), reverse=True)

Records with equal ages retain their name order from the first sort.

Decide how missing values behave

Direct indexing raises KeyError for a missing field. A default is appropriate only if its ordering matches your data model:

ordered = sorted(users, key=lambda user: user.get("age", 0))

This treats missing age as zero, which may be misleading. It also does not replace an explicitly stored None. For numeric ages with missing or None values placed last:

ordered = sorted(
    users,
    key=lambda user: (
        user.get("age") is None,
        user.get("age") if user.get("age") is not None else 0,
    ),
)

FAQ

Is sorting stable? Yes. Equal keys retain their original relative order, including with reverse=True.

Can I sort date strings? Uniform, valid YYYY-MM-DD strings sort chronologically. Do not generalize this to arbitrary date formats or timestamps with differing offsets; parse and normalize them first.

What if the field mixes strings and numbers? An integer and a string cannot be ordered directly in Python 3. Validate or normalize the key values rather than relying on accidental input types.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting