Python NamedTuple example: Creating a food dictionary

Python NamedTuple Data Type: Exercise-3 with Solution

Write a Python program that creates a dictionary where keys are food names and prices are instances of the Food named tuple.

Sample Solution:


from collections import namedtuple
# Define a NamedTuple named 'Food' with fields 'name' and 'price'
Food = namedtuple("Food", ["name", "price"])
# Create instances of the Food NamedTuple
food1 = Food("Pizza", 11.90)
food2 = Food("Burger", 7.45)
food3 = Food("Salad", 5.45)
# Create a dictionary where keys are food names and values are Food instances
food_dict = {
    food1.name: food1,
    food2.name: food2,
    food3.name: food3
# Access and print values using dictionary keys
for food_name, food_info in food_dict.items():
    print(f"Food: {food_name}, Price: ${food_info.price:.2f}")


Food: Pizza, Price: $11.90
Food: Burger, Price: $7.45
Food: Salad, Price: $5.45

In the exercise above, we first define a NamedTuple named "Food" with the fields 'name' and 'price'. We then create instances of the "Food" NamedTuple with different food items and their prices. Next, we create a dictionary named 'food_dict', whose keys are food names and whose values are instances of the "Food" NamedTuple. Finally, we iterate through the dictionary and print the food names and their corresponding prices.


Flowchart: Python NamedTuple example: Creating a food dictionary.

Previous: Python NamedTuple example: Point coordinates.
Next: Python NamedTuple example: Defining a student NamedTuple.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.