Shopping_list= [
{"title":"cheese","quantity":50,"unit":"gm"},
{"title":"cheese","quantity":40,"unit":"gm"},
{"title":"curd","quantity":20,"unit":"gm"}
]我只想在标题匹配时对数量进行求和,然后想要下面的输出列表:
final_list = [
{"title":"cheese","quantity":90,"unit":"gm"},
{"title":"curd","quantity":20,"unit":"gm"}]发布于 2022-07-29 07:52:14
您可以使用排序按“标题”和“单位”。然后根据这个排序列表分组,并计算每个组的和。
from itertools import groupby
def key_func(k):
return k['title'],k['unit']
Shopping_list = sorted(Shopping_list, key=key_func)
result = []
for key,value in groupby(Shopping_list, key_func):
total = 0
for item in list(value):
total+= item['quantity']
result.append({'title': key[0],'quantity':total, 'unit': key[1]})
print(result)发布于 2022-07-29 07:54:46
shopping_list= [
{"title":"cheese","quantity":50,"unit":"gm"},
{"title":"cheese","quantity":40,"unit":"gm"},
{"title":"curd","quantity":20,"unit":"gm"}
]
agg = {}
for entry in shopping_list:
if entry["title"] not in agg:
agg[entry["title"]] = entry
else:
agg[entry["title"]]["quantity"] += entry["quantity"]
final_list = list(agg.values())发布于 2022-07-29 07:57:28
您所需要做的就是遍历Shopping_list并检查result列表中的dicts的title (通过简单的线性搜索)。如果有带有该标题的字典,则增加quantity的数量,否则该标题是新的,然后将字典转移到result列表。
Shopping_list = [
{"title": "cheese", "quantity": 50, "unit": "gm"},
{"title": "cheese", "quantity": 40, "unit": "gm"},
{"title": "curd", "quantity": 20, "unit": "gm"},
]
result = []
for d1 in Shopping_list:
for d2 in result:
if d2["title"] == d1["title"]:
d2["quantity"] += d1["quantity"]
break
else:
result.append(d1)
print(result)https://stackoverflow.com/questions/73162519
复制相似问题