Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSenior Deep-DivesModule 10 · Production idioms (modern Python)TypedDict + NotRequired — JSON shapes as typespredict148 / 161
+150 XP
Task
📝 **Task:** Predict the 7-line output. A User TypedDict has 2 required keys (email, name) and 2 NotRequired keys (age, address). Construct one User with required-only, one with all keys. Then dump __required_keys__ and __optional_keys__ sorted (frozensets don't have deterministic iteration order, so sort for predictability). 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

from typing import TypedDict, NotRequired


class Address(TypedDict):
    street: str
    city: str


class User(TypedDict):
    email: str
    name: str
    age: NotRequired[int]
    address: NotRequired[Address]


# Required keys only
u1: User = {"email": "a@b.com", "name": "Ada"}
print(u1)
print(type(u1).__name__)
print(sorted(u1.keys()))

# All keys including NotRequired
u2: User = {
    "email": "b@c.com",
    "name": "Bob",
    "age": 30,
    "address": {"street": "1st", "city": "NYC"},
}
print(u2["address"]["city"])
print(u2.get("age", 0))

# Reflection on the TypedDict itself
print(sorted(User.__required_keys__))
print(sorted(User.__optional_keys__))

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…