python 搜索并合并多个具有相同键、和值的字典

e3bfsja2  于 2023-03-28  发布在  Python
关注(0)|答案(2)|浏览(129)

我从menu dict中得到一个成分列表,在该列表中,对于每个菜单项,有几个包含几种成分的dicts:

{'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}
}

目前我找不到方法来合并匹配的成分,它只显示最后一个与重复的名称。如果我.append all in a list,list.count(y)〉2,它仍然忽略第一个示例。请记住,有几个dicts,它是一个潜在的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)
4smxwvx5

4smxwvx51#

我希望我理解你的问题是正确的。你可以试试:

lst = [
    {"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},
]

out = {}
for d in lst:
    out.setdefault(d["ingredient_name"], {}).update(measure=d["measure"])
    out[d["ingredient_name"]]["quantity"] = (
        out[d["ingredient_name"]].get("quantity", 0) + d["quantity"]
    )

print(out)

图纸:

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

fykwrbwg2#

list = []
  final_list = {}
  cook_book = makecookbook(recipe_file) ## function creating dict based on recipe.txt, with key = cook_book['dish'], value = list of ingredients 
  ingridients_dict = {key: cook_book[key] for key in dishes}
  for items in ingridients_dict.values():
    for ingridients in items:
      list.append(ingridients)
  for ingr in list:
      final_list.setdefault(ingr["ingredient_name"], {}).update(measure=ingr["measure"])
      final_list[ingr["ingredient_name"]]["quantity"] = (
        final_list[ingr["ingredient_name"]].get("quantity", 0) + ingr["quantity"] * person_count)
  return final_list

pprint(shop_list_by_dish(['xxx', 'yyy', 'vvv'], person_count), indent=1, width=70)

相关问题