Skip to main content

How to Sort a List of Dictionaries by a Key in Python

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

A list of dictionaries is how Python often holds records: rows from a file, items from an API, books in a catalogue. To put the records in order by one field, such as a year, you give sorted() a key that picks that field out of each dictionary. This guide sorts three books by year on Python 3.15.2.

Syntax​

Syntax
sorted(<list of dictionaries>, key=lambda <item>: <item>[<key>])
PartWhat it means
<list of dictionaries>The records to sort. sorted() returns a new list and leaves this one as it is
lambda <item>: <item>[<key>]A one-line function that takes one dictionary and returns the value to sort by
<key>The dictionary key to sort on, such as "year". Every dictionary needs it

Python's Sorting Techniques guide explains that the key function is "called on each list element prior to making comparisons", and that "A common pattern is to sort complex objects using some of the object's indices as keys."

The Example​

Three books, each a dictionary with a title and a year, are sorted from oldest to newest and printed one per line.

Prerequisites​

  • uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

sort_books.py
books = [
{"title": "Dune", "year": 1965},
{"title": "Neuromancer", "year": 1984},
{"title": "Foundation", "year": 1951},
]

for book in sorted(books, key=lambda book: book["year"]):
print(book["year"], book["title"])

The sort_books.py script in a macOS-style code window: three book dictionaries with a title and a year, looped over in the order of sorted(books, key=lambda book: book["year"]) and printed as year and title.

  • lambda book: book["year"] takes one book and returns its year.
  • sorted() compares the years, not the dictionaries, and returns the books in that order.
  • The loop prints each book's year and title.

Step 2: Run It​

Terminal
uv run python sort_books.py
Output
1951 Foundation
1965 Dune
1984 Neuromancer

The terminal after uv run python sort_books.py: 1951 Foundation, 1965 Dune and 1984 Neuromancer, oldest first.

The books came out oldest first, while the list itself kept its original order. The command works unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Sorting without a key: sorted(books)TypeError: '<' not supported between instances of 'dict' and 'dict'Say which value to compare: key=lambda book: book["year"]
One dictionary lacks the keyKeyError: 'year'Give every record the key, or use book.get("year", 0) to supply a value for records without it
Sorting numbers stored as text, such as "95" and "120"Text order: "120" comes before "95", because "1" comes before "9"Convert in the key: key=lambda book: int(book["pages"])

Troubleshooting​

SymptomLikely causeFix
TypeError: '<' not supported between instances of 'dict' and 'dict'Python can't compare whole dictionariesAdd key=
KeyError from inside the lambdaA record doesn't have that keyCheck the key's spelling, or use .get() with a default
The list is in the old order after sortingsorted() returns a new listUse the returned list, or sort in place with books.sort(key=...)

FAQ​

How do I sort newest first?​

Add reverse=True: sorted(books, key=lambda book: book["year"], reverse=True) gives Neuromancer, Dune and Foundation.

Is there a shorter way to write the key?​

operator.itemgetter("year") does the same as lambda book: book["year"]. The sorting guide calls these functions "simpler and faster". With from operator import itemgetter, sorted(books, key=itemgetter("year")) gives Foundation, Dune and Neuromancer.

How do I sort the list itself instead of making a new one?​

Call books.sort(key=lambda book: book["title"]). It reorders books and returns None, so don't assign its result.

Conclusion​

sorted(books, key=lambda book: book["year"]) put the books in order by year, comparing only that one value from each dictionary. Every record needs the key, and numbers stored as text need int() in the key.

Additional Resources​