Skip to main content

1. What is TypedDict?

TypedDict defines the expected structure of a dictionary using type hints.
It is still a normal Python dictionary:
TypedDict is mainly for static type checking. It does not perform runtime validation.

Practice

Define a Movie TypedDict with fields title (str), year (int), and rating (float). Create a valid instance of it.

2. Required Keys

By default, all keys are required.

Practice

Define a Product TypedDict with fields name (str) and price (float). Create an instance that misses a required key and note what a static type checker would report.

3. Union Types with |

Modern Python supports | for union types.
age is required, but its value can be int or None.

Important

Practice

Define a User TypedDict where email is str | None. Create an instance with email as None and another with a string email.

4. Optional Keys with NotRequired

Use NotRequired when the key itself can be omitted.
Both are valid:
To make the key optional and allow None:
Now all are valid:

Practice

Define a Book TypedDict where title (str) and author (str) are required, but pages (int) and genre (str | None) are NotRequired. Create an instance without pages and genre, and another with both.

5. TypedDict vs Pydantic

Simple rule:

6. TypedDict in LangGraph

TypedDict is commonly used to define LangGraph state.
Initially:
After retrieval:
After generation:
This makes TypedDict particularly useful for state that evolves as it moves between LangGraph nodes.

Practice

Define an LLMState TypedDict for a translation agent with required key original_text (str), and optional keys source_language (NotRequired[str]), target_language (NotRequired[str]), and translated_text (NotRequired[str]). Create instances representing the state at different stages.

7. Quick Reference

8. Key Takeaway


Practice & Exercises

To reinforce what you’ve learned in this section (defining TypedDicts, required vs optional keys, union types, and graph states), practice with these interactive notebooks:

Follow-Along Practice

Practice defining dictionary structures, working with Required and NotRequired keys, using modern Union types, and modeling LangGraph states.💻 VS Code | 🚀 Colab | 📥 Download

Practice Exercises

Test your knowledge by building schemas for Movies, Products, Users, Books, and translation LLMStates with proper type hinting.💻 VS Code | 🚀 Colab | 📥 Download