字典,用于切片和切片菜单的嵌套值



如何创建一个函数来计算膳食和单个菜肴的卡路里?

我有两本字典

meals = {"Happy Meal": ["Cheese Burger", "French Fries", "Coca Cola"], "Best Of Big Mac": ["Big Mac", "French Fries", "Coca Cola"], "Best Of McChicken": ["McChicken", "Salad", "Sprite"]}
poor_calories = {"Hamburger": 250, "Cheese Burger": 300, "Big Mac": 540, "McChicken": 350, "French Fries": 230, "Salad": 15, "Coca Cola": 150, "Sprite": 150}

这是我到目前为止所做的:(我没有建立两个字典的连接并创建一个具有有效循环的函数)

print(meals.get("Happy Meal"))
print(meals.get("Best Of Big Mac"))
print(meals.get("Best Of McChicken"))

def advanced_calories_counter(meals, key):
return meals.get(key, "item_name not found")
print(advanced_calories_counter(meals,'Happy Meal'))
menu = {**meals, **poor_calories}
print(menu)
for key in menu:
print(key)
def menu4(key):
for calories, dish in poor_calories.items():
for meal, dish in meals.items():
print(calories, dish, meal, meals[key][value])
print(menu4("Happy Meal"))

使用推导式:

out = {meal: {dish: poor_calories[dish] for dish in dishes}
for meal, dishes in meals.items()}
print(out)
#Output:
{'Happy Meal': {'Cheese Burger': 300, 'French Fries': 230, 'Coca Cola': 150},
'Best Of Big Mac': {'Big Mac': 540, 'French Fries': 230, 'Coca Cola': 150},
'Best Of McChicken': {'McChicken': 350, 'Salad': 15, 'Sprite': 150}}

如果您想要每份菜单的总热量:

out2 = {meal: sum(poor_calories[dish] for dish in dishes) 
for meal, dishes in meals.items()}
print(out2)
# Output
{'Happy Meal': 680, 'Best Of Big Mac': 920, 'Best Of McChicken': 515}

使用operator.itemgetter和推导式:

from operator import itemgetter
{meal: dict(zip(items, itemgetter(*items)(poor_calories))) for meal, items in meals.items()}

{'Best Of Big Mac': {'Big Mac': 540, 'Coca Cola': 150, 'French Fries': 230},
'Best Of McChicken': {'McChicken': 350, 'Salad': 15, 'Sprite': 150},
'Happy Meal': {'Cheese Burger': 300, 'Coca Cola': 150, 'French Fries': 230}}

获取膳食卡路里:

{meal: sum(itemgetter(*items)(poor_calories)) for meal, items in meals.items()}

{'Best Of Big Mac': 920, 'Best Of McChicken': 515, 'Happy Meal': 680}

相关内容

  • 没有找到相关文章

最新更新