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.
Python code
16 linesfrom 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
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
- Use a function-based syntax: User = TypedDict('User', {'name': str, 'age': int, 'email': str})
- 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
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.