You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并相同食材名字典并累加数量?Python技术求助

问题

从菜单字典中获取了一份食材列表,列表中每个菜品对应多个食材字典,示例如下:

{'ingredient_name': 'A', 'measure': 'kg', 'quantity': 1}
{'ingredient_name': 'B', 'measure': 'ml', 'quantity': 50}
{'ingredient_name': 'A', 'measure': 'kg', 'quantity': 2}
{'ingredient_name': 'C', 'measure': 'count', 'quantity': 2}
...

期望输出格式为:

{
    'A': {'measure': 'kg', 'quantity': 3},
    'B': {'measure': 'ml', 'quantity': 50},
    'C': {'measure': 'count', 'quantity': 2}
}

目前无法实现同名食材的合并,结果仅保留重复食材名的最后一项;若将所有字典存入列表,使用list.count()判断重复也会忽略第一个实例。需处理的字典数量可能超过50个,当前函数代码如下:

ingridients_dict = {key: cook_book[key] for key in dishes}
for items in ingridients_dict.values():
  for ingredients in items:
    x = ingredients['quantity'] * person_count
    ingredients.update({'quantity': x})
    final_list[ingridients.pop('ingredient_name')] = ingredients
return final_list

pprint(shop_list([dishes], person_count: int), indent=1, width=70)

请求帮助实现同名食材的合并及数量累加。

解决方案

核心问题是直接用食材名作为键覆盖final_list中的值,导致重复食材只保留最后一项。需要先判断食材是否已存在,再做数量累加,而非直接赋值。

修改后的代码如下:

def shop_list(dishes, person_count):
    final_list = {}
    # 遍历选中的每道菜品
    for dish in dishes:
        # 获取当前菜品对应的食材列表
        for ingredient in cook_book[dish]:
            # 复制食材字典,避免修改原菜单数据
            ing_copy = ingredient.copy()
            # 计算对应人数的食材需求量
            ing_copy['quantity'] *= person_count
            ing_name = ing_copy.pop('ingredient_name')
            
            # 处理同名食材的合并逻辑
            if ing_name in final_list:
                final_list[ing_name]['quantity'] += ing_copy['quantity']
            else:
                final_list[ing_name] = ing_copy
    return final_list

# 调用示例(需确保全局变量cook_book已正确定义)
pprint(shop_list(dishes, person_count), indent=1, width=70)

关键优化细节:

  • 遍历食材时复制字典,避免修改原cook_book的数据
  • 对每个食材名做存在性检查:
    • 若已存在,直接累加quantity数值
    • 若不存在,将处理后的食材字典加入结果集
  • 修正了原代码中的拼写错误(ingridients应为ingredient)和调用语法错误(类型注解person_count: int仅用于函数定义,调用时直接传数值即可)

内容的提问来源于stack exchange,提问作者Blandon 93

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 21:12:29