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:
Code:
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}")
Output:
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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/extended-data-types/python-extended-data-types-index-namedtuple-exercise-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics