I want to append different dictionaries having the key as the meal_name
and having total_calories
and total_protein
as a tuple being the value of the dictionary without overwriting the original dictionaries under the main dictionary having date as the key value.
I tried using the code below to add the new dictionary but it overwrites the previous one.
date = input("Enter the date in (Day-Month-Year) format: ")
name = input("Enter the name of the meal: ")
current_meal[name] = (total_calories, total_protein)
meal_data[date] = current_meal
This is what the dictionary looks like:
{'23-07-2024': {'Smoothie': (245.0, 17.0)}}
Suppose I want to add a new meal to the existing date without overwriting the Smoothie dictionary. Is this possible.
You can use the if-else statement to check whether the current date is in the dictionary.
date = input("Enter the date in (Day-Month-Year) format: ")
name = input("Enter the name of the meal: ")
if date in meal_data: # If date is already in meal_date then set the current_meal to existing meal
current_meal = meal_data[date]
else: # if not then set it to empty dict
current_meal = {}
current_meal[name] = (total_calories, total_protein) # Adding new meal to the current_meal
meal_data[date] = current_meal
OUTPUT