Convert a Dict to a NamedTuple
Intermediate · Write the code · from NamedTuple vs TypedDict vs Dataclass: Which to Choose?
From the lesson: NamedTuple vs TypedDict vs Dataclass: Which to Choose?
Python gives you three popular ways to bundle related data together: NamedTuple, TypedDict, and dataclass. Each one solves a slightly different problem.
Read the lessonGiven a dictionary data, create a NamedTuple class called Book with fields title (str), author (str), and pages (int). Convert the dictionary to a Book instance using ** unpacking, then print the result.
from typing import NamedTuple
data = {'title': 'Python 101', 'author': 'Pat', 'pages': 250}
# Create the Book NamedTuple
# Convert data dict to a Book and print it
More NamedTuple and TypedDict exercises
- Create a NamedTuple for RGB ColorsBeginner
- Build a TypedDict for API ResponseBeginner
- Predict the Output: ImmutabilityIntermediate
- Choose the Right ContainerAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz