Model Records with TypedDict and NamedTuple
Core idea
TypedDict describes dictionary keys and value types statically. Keys are required by default; NotRequired[T] (Python 3.11+) permits omission of a specific key. NamedTuple defines a tuple subclass with named, typed fields. It is useful for positional immutable records; the referenced field objects may still be mutable.
from typing import TypedDict, NotRequiredclass Device(TypedDict): name: str zone: NotRequired[int]record: Device = {'name': 'meter'}print(record['name'], record.get('zone', 0))print(type(record).__name__)The optional key may be absent, and the actual object is a dict.
Model a named positional record
from typing import NamedTupleclass Reading(NamedTuple): label: str value: intr = Reading('A', 9)print(r.label, r[1])print(r._replace(value=10).value, r.value)Named access and positional access agree; _replace produces a new record.
Common mistake
TypedDict does not validate JSON at runtime and cannot be used as an isinstance target. NotRequired[int] differs from a required key of type int | None. NamedTuple field assignment is not supported.
Practice
Model a record with required ID and optional note using TypedDict, then a two-field immutable record using NamedTuple. Explain their runtime differences.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
TypedDict and NamedTuple
Check your understanding of typeddict and namedtuple.
What is printed?
from typing import TypedDictclass R(TypedDict): count: intr: R = {'count': 3}print(type(r).__name__)What is printed?
from typing import NamedTupleclass P(NamedTuple): x: int y: intp=P(2, 4)print(p.y, p[0])What does NotRequired[int] describe?
Which record supports named and positional field access?