1. What is TypedDict?
TypedDict defines the expected structure of a dictionary using type hints.
TypedDict is mainly for static type checking. It does not perform runtime validation.
Practice
Define aMovie TypedDict with fields title (str), year (int), and rating (float). Create a valid instance of it.
Solution
Solution
2. Required Keys
By default, all keys are required.Practice
Define aProduct 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.
Solution
Solution
3. Union Types with |
Modern Python supports | for union types.
age is required, but its value can be int or None.
Important
Practice
Define aUser TypedDict where email is str | None. Create an instance with email as None and another with a string email.
Solution
Solution
4. Optional Keys with NotRequired
Use NotRequired when the key itself can be omitted.
None:
Practice
Define aBook 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.
Solution
Solution
5. TypedDict vs Pydantic
Simple rule:
6. TypedDict in LangGraph
TypedDict is commonly used to define LangGraph state.
TypedDict particularly useful for state that evolves as it moves between LangGraph nodes.
Practice
Define anLLMState 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.
Solution
Solution
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