Typed Dictionaries with typing.TypedDict
`TypedDict` declares expected dictionary keys and their value types. At runtime it remains a standard dictionary, but type checkers catch missing or misspelled keys 📋.
from typing import TypedDict
class UserProfile(TypedDict):
id: int
username: str
is_active: bool
user: UserProfile = {
"id": 101,
"username": "mona",
"is_active": True
}
print(user["username"]) # 'mona' 📋
# 93. Typed Dictionaries with typing.TypedDict `TypedDict` declares expected dictionary keys and their value types. At runtime it remains a standard dictionary, but type checkers catch missing or misspelled keys 📋. ```python from typing import TypedDict class UserProfile(TypedDict): id: int username: str is_active: bool user: UserProfile = { "id": 101, "username": "mona", "is_active": True } print(user["username"]) # 'mona' 📋 ``` `TypedDict` gives you the speed and JSON-compatibility of standard dicts while providing compile-time schema validation! 📋 --- ### Question What is the runtime type of an object created using a `TypedDict` specification? 🧠- [ ] a. A standard Python `dict` with zero runtime wrapper overhead 📋 - [ ] b. A specialized immutable C struct - [ ] c. A SQLite database cursor - [ ] d. A tuple wrapped in a metaclass --- ### Challenge Create `class Movie(TypedDict): title: str; year: int`. Create an instance `m: Movie = {'title': 'Inception', 'year': 2010}` and print `m['year']`. 🎯 <details> <summary>Solution</summary> ```python from typing import TypedDict class Movie(TypedDict): title: str year: int m: Movie = {"title": "Inception", "year": 2010} print(m["year"]) ``` </details>