Types

TypedDict

TypedDict describes dictionaries with known string keys.

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: 98
USER TYPEDDICTid: intname: stractive: bool
TypedDict gives each key a typed value, so `obj['x']` is checked against the declared shape.

At runtime, a TypedDict value is still a plain dictionary.

Source

print(isinstance(record, dict))
print(type(record).__name__)

Output

True
dict

NotRequired 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

none

Notes

See also

Run the complete example

Example code

Expected output

Ada: 98
True
none

Execution time appears here after you run the example.