【问题标题】:Dictionaries, nested values to slice and dice menus字典、嵌套值对菜单进行切片和切块
【发布时间】:2021-11-19 22:25:04
【问题描述】:

我如何创建一个函数来计算餐食和单菜组合的卡路里?

我有两本字典

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"))

【问题讨论】:

  • 您希望该功能如何工作?
  • 例如如果我调用 Happy Meal,我想要以下输出:芝士汉堡 300、炸薯条 230、可口可乐 150。我无法连接
  • def menu(menu_name): {food: poor_calories.get(food, food + ' not found') for food in menu_name}

标签: python dictionary nested


【解决方案1】:

使用理解:

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}

【讨论】:

  • 非常感谢!我觉得太复杂了
【解决方案2】:

使用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}

【讨论】:

    猜你喜欢
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多