How can I create a function that will enable to calculate calories of a combination of both meals and individual dishes?
I have two dictionaries
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}
This is what I have so far: (I'm failing in building a connection of the two dictionaries and creating a function with a loop that works.)
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"))
CodePudding user response:
Use a comprehension:
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}}
If you want the total calories per menu:
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}
CodePudding user response:
Using operator.itemgetter
and a comprehension:
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}}
And to get the meal calories:
{meal: sum(itemgetter(*items)(poor_calories)) for meal, items in meals.items()}
{'Best Of Big Mac': 920, 'Best Of McChicken': 515, 'Happy Meal': 680}