Types
TypedDict
Use TypedDict for JSON-like records that remain dictionaries.
Source
from typing import TypedDict
class User(TypedDict):
name: str
score: int
def describe(user: User) -> str:
return f"{user['name']}: {user['score']}"
record: User = {"name": "Ada", "score": 98}
print(describe(record))Output
Ada: 98At runtime, a TypedDict value is still a plain dictionary.
Source
print(isinstance(record, dict))
print(type(record).__name__)Output
True
dictNotRequired marks a key that type checkers should treat as optional. Runtime lookup still uses normal dictionary tools such as get().
Source
from typing import NotRequired
class UserWithNickname(TypedDict):
name: str
score: int
nickname: NotRequired[str]
record: UserWithNickname = {"name": "Ada", "score": 98}
print(record.get("nickname", "none"))Output
noneNotes
- Use
TypedDictfor dictionary records from JSON or APIs. - Type checkers understand required and optional keys.
- Runtime behavior is still ordinary dictionary behavior.
See also
- prerequisite: Dictionaries
- next depth: JSON
- prerequisite: Dataclasses
- next depth: Structured Data Shapes
Run the complete example
Expected output
Ada: 98
True
none
Execution time appears here after you run the example.