Course contentsShow
← Python
Lesson 575 of 1,0609. Type Safety and Code QualityFree lesson

Defining Dictionary Schemas with TypedDict for Required Keys

Specify expected dictionary structures including required and optional keys using TypedDict to enhance static type safety.

In this lesson, you will learn how to enforce a specific structure for your dictionaries using TypedDict to ensure that every required key is present and correctly typed.

The Limitation of Basic Dictionaries

When you annotate a dictionary using standard syntax like dict[str, Any], Python’s static type checkers (like mypy) have no way of knowing which specific keys are expected. If your code expects a user dictionary to always have an id and a username, a standard dict annotation won't warn you if one of those keys is missing, leading to KeyError exceptions at runtime.

Enforcing Schemas with TypedDict

TypedDict allows you to define a "schema" for your dictionaries. By subclassing TypedDict from the typing module, you can explicitly declare the keys you need and the types of their values.

from typing import TypedDict

class UserProfile(TypedDict):
    username: str
    id: int
    is_admin: bool

# Correct usage
user: UserProfile = {"username": "dev_guru", "id": 101, "is_admin": False}

# Static type checkers will flag this as an error because 'id' is missing
incomplete_user: UserProfile = {"username": "dev_guru", "is_admin": False}

By defining UserProfile as a TypedDict, the type checker treats the dictionary as having a fixed structure. If you attempt to initialize the dictionary without the id key, or if you provide a value of the wrong type (e.g., passing a string for id), your IDE or static checker will highlight the issue immediately.

This approach shifts the burden of validation from runtime to development time, making your data-handling code significantly more robust. Because this is a type-level construct, it does not add runtime overhead, yet it provides the documentation and safety of a formal schema.

Key Takeaway: Use TypedDict to define precise dictionary schemas that enforce the presence and type consistency of required keys during static analysis.