将多个字典附加到嵌套字典的特定键

问题描述 投票:0回答:1

我想附加不同的字典,其键作为meal_name,并且total_calories和total_ Protein作为元组作为字典的值,而不覆盖以日期作为键值的主字典下的原始字典。

我尝试使用下面的代码添加新词典,但它覆盖了前一个词典。

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

这就是字典的样子: {'23-07-2024': {'冰沙': (245.0, 17.0)}} 假设我想在现有日期中添加新餐而不覆盖 Smoothie 字典。这可能吗?

python dictionary multidimensional-array nested
1个回答
0
投票

您可以使用 if-else 语句来检查当前日期是否在字典中。

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

输出

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.