How to Use TypedDict for Structured Dict Typing in Python

Define and use TypedDict to add type hints to dictionaries, improving code clarity and enabling static type checking in your Python projects.

Easy Python 3.8+ Aug 9, 2026 Testing & modern typing 12 views 0 copies

Python code

16 lines
Python 3.8+
from typing import TypedDict


class User(TypedDict):
    name: str
    age: int
    email: str


def greet(user: User) -> str:
    return f"Hello {user['name']}, age {user['age']}, contact {user['email']}"


if __name__ == "__main__":
    alice: User = {"name": "Alice", "age": 30, "email": "alice@example.com"}
    print(greet(alice))

Output

stdout
Hello Alice, age 30, contact alice@example.com

How it works

TypedDict is a special construct in Python's typing module that lets you specify the expected keys and value types for a dictionary. When you annotate a variable or parameter with a TypedDict, type checkers like mypy or Pyright can verify that the dictionary conforms to the declared structure. This improves code readability and maintainability by making the data contract explicit. TypedDict is especially useful when working with JSON-like data structures in applications such as API clients or configuration handlers.

Common mistakes

  • Forgetting to import TypedDict from typing.
  • Using TypedDict to create a class that you instantiate normally; TypedDict is only for type hints, not for runtime behavior.
  • Expecting TypedDict to enforce runtime validation; it does not, it's purely for static type checking.

Variations

  1. Use a function-based syntax: User = TypedDict('User', {'name': str, 'age': int, 'email': str})
  2. Make all fields optional with total=False in the TypedDict definition.

Real-world use cases

  • Annotating API response payloads to ensure the correct keys are accessed throughout your codebase.
  • Modeling configuration dictionaries in a settings file with clear structural type hints.
  • Defining schemas for database records fetched as dictionaries, improving maintainability and static checks.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.