Sub topic 14
Describing dictionary shapes with TypedDict
This chapter assumes you know how to annotate collections such as dict[str, int], and that you have run a static checker like mypy or pyright. It covers how to type a dictionary whose keys are fixed and whose values have different types.
The problem with dict[str, object]
Data from JSON files or web APIs often arrives as a dictionary with known keys. dict[str, int] does not fit it, because the values differ in type. dict[str, object] accepts the data, but the checker then knows nothing about each value. It cannot tell you that movie["year"] is an int.
Defining a TypedDict
A TypedDict is a class that gives each key of a plain dictionary its own type. You write it like a class with annotated fields.
from typing import TypedDict
class Movie(TypedDict):
title: str
year: int
movie: Movie = {"title": "Alien", "year": 1979}
print(movie["title"])At runtime movie is an ordinary dict. The class exists only for the checker. You can still use movie.get(...), loop over it, or pass it to json.dumps.
What the checker catches
Given the Movie class above, a checker reports errors for these lines:
from typing import TypedDict
class Movie(TypedDict):
title: str
year: int
missing: Movie = {"title": "Alien"} # missing key "year"
wrong: Movie = {"title": "Alien", "year": "1979"} # "year" must be int
extra: Movie = {"title": "Alien", "year": 1979, "rating": 5} # unknown keyIt also flags movie["director"], because that key is not declared. The exact wording differs between mypy and pyright.
Optional keys
By default every key is required. Mark a key as optional with NotRequired, available from typing in Python 3.11 and later.
from typing import NotRequired, TypedDict
class Movie(TypedDict):
title: str
year: int
rating: NotRequired[float]
movie: Movie = {"title": "Alien", "year": 1979}
if "rating" in movie:
print(movie["rating"])The in check narrows the type. Without it, the checker warns that movie["rating"] may be missing. Alternatively, pass total=False to make every key optional.
Common errors
- Expecting runtime validation.
Movie({"title": 1})does not raise an error. The interpreter does not check TypedDict contents. If data comes from outside your program, validate it with a library or your own code. - Using isinstance.
isinstance(x, Movie)raises aTypeError. A TypedDict cannot be used in runtime type checks. - Using attribute access.
movie.titlefails. Keys are read withmovie["title"]. If you want attributes, use a dataclass. - Passing a plain
dict[str, object]. The checker rejects it where aMovieis expected, because it cannot prove the keys exist.
Exercise
Write a TypedDict named User with a required name (str), a required id (int), and an optional email (str). Then explain what happens at runtime if you create a User with id set to the string "7".
Show answer
from typing import NotRequired, TypedDict class User(TypedDict): name: str id: int email: NotRequired[str] At runtime, nothing happens. The value is a plain dict and the interpreter does not check types, so the program runs. A static checker such as mypy or pyright reports that "id" must be an int.