Question

Appending multiple dictionaries to specific key of a nested dictionary

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.

 2  59  2
1 Jan 1970

Solution

 1

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

enter image description here

2024-07-23
Sharim09

Solution

 1

I would suggest making use of the nested key in the dictionary, like this:

meal_dict = {}

meal_dict['23-07-2024'] =  {'Smoothie': (245.0, 17.0)}
meal_dict['23-07-2024']['Salad'] = (400.0, 10.0)

Which outputs:

{'23-07-2024': {'Smoothie': (245.0, 17.0), 'Salad': (400.0, 10.0)}}
2024-07-23
ellenbet