Skip to content
Project: Building a Calorie Intake Calculator
As a Software Engineer in a Health and Leisure company, your task is to add a new feature to the app: a calorie and nutrition calculator. This tool will calculate and display total calories, sugars, fats, and other nutritional values for different foods based on user input.
You have been provided with the nutrition.json dataset, which contains the necessary nutritional information for various foods. Each value in the dataset is per 100 grams of the food item. The dataset has already been read and loaded for you as the dictionary nutrition_dict.
Dataset Summary
nutrition.json
| Column | Description |
|---|---|
food | The name of the food. |
calories | The amount of energy provided by the food, measured in kilocalories (kcal) per 100 grams. |
total_fat | The total fat content in grams per 100 grams. |
protein | The protein content in grams per 100 grams. |
carbohydrate | The total carbohydrate content in grams per 100 grams. |
sugars | The amount of sugars in grams per 100 grams. |
Let's Get Started!
This project is a great opportunity to build a real-world feature from scratch, showcasing your development skills and making a meaningful impact on users' health and wellness.
import json # Import the json module to work with JSON files
# Open the nutrition.json file in read mode and load its content into a dictionary
with open('nutrition.json', 'r') as json_file:
nutrition_dict = json.load(json_file) # Load the JSON content into a dictionary
# Display the first 3 items of the nutrition dictionary
list(nutrition_dict.items())[:3]# Creating the function
def nutritional_summary(food_dict):
# Initialize totals
totals = {
"calories": 0,
"total_fat":0,
"protein": 0,
"carbohydrate": 0,
"sugars": 0
}
# Loop through input foods
for food, grams in food_dict.items():
if food not in nutrition_dict:
return food
#Scaling factor (per 100g)
factor = grams/ 100
# Accumlate nutrition
totals["calories"] += nutrition_dict[food]["calories"] * factor
totals["total_fat"] += nutrition_dict[food]["total_fat"] * factor
totals["protein"] += nutrition_dict[food]["protein"] * factor
totals["carbohydrate"] += nutrition_dict[food]["carbohydrate"] * factor
totals["sugars"] += nutrition_dict[food]["sugars"] * factor
return totals
# Foods in the nutrition dict
food_list = list(nutrition_dict.keys())
food_list[:20]# Putting our function to test
nutritional_summary({"Nuts, pecans": 200,
"Taro leaves, raw": 300})