我想基于相同的键值对合并字典列表。我有一个字典列表
[{'id':1, 'total':100,'free_from':250},{'id':2,....},{'id':1,......}]
我想以此结构创建一个新的词典列表,但是如果两个词典的ID相同,则应添加其总数,而不是将词典添加到新列表中。
这是词典列表
products = [{'id':1,'total':20,'free_from':250,},{'id':2,'total':30,'free_from':150},{'id':1,'total':10,'free_from':250,},{'id':1,'total':10,'free_from':250},{'id':2,'total':40,'free_from':150, }]
,预期结果是
[{ 'id': 1,'total': 40, 'free_from': 250}, {'id': 2,'total': 70, 'free_from': 150}]
我设法通过使用以下方法来实现这一目标。但是,如果有人可以帮助我找到一种更好的方法,那将是非常有帮助的。
category_delivery_list=[]
products = [
{
'id':1,
'total':20,
'free_from':250,
},{
'id':2,
'total':30,
'free_from':150,
},{
'id':1,
'total':10,
'free_from':250,
},{
'id':1,
'total':10,
'free_from':250,
},{
'id':2,
'total':40,
'free_from':150,
}
]
for data in products:
if category_delivery_list:
index = None
for count, cat in enumerate(category_delivery_list):
if cat['id'] == data['id']:
index=count
if index >= 0:
category_delivery_list[index]['total'] += data['total']
category_delivery_list[index]['free_from'] = data['free_from']
else:
category_delivery_list.append({
'id':data['id'],
'total':data['total'],
'free_from':data['free_from']
})
else:
category_delivery_list.append({
'id':data['id'],
'total':data['total'],
'free_from':data['free_from']
})
print(category_delivery_list)
答案 0 :(得分:0)
执行此操作的一种好方法是通过临时字典:
temp = {}
for data in products:
if data["id"] in temp:
temp[data["id"]]["total"] += data["total"]
temp[data["id"]]["free_from"] += data["free_from"]
else:
temp[data["id"]] = data.copy()
category_delivery_list = list(temp.values)
这将创建一个临时词典id
-> {'id':.., 'total':..., 'free_from':...}
,然后遍历列表并添加新条目或添加到现有条目。