我有一个这样的字典列表
[
{'id':1,'product_id':20,'price':50,'quantity':1, 'name':'product_2'},
{'id':2,'product_id':20,'price':50,'quantity':1, 'name':'product_2'},
{'id':3,'product_id':30,'price':20,'quantity':4, 'name':'product_3'},
]
我如何将这个列表分组并得到这样的结果
[
{'id':1,'product_id':20,'price':100,'quantity':2, 'name':'product_2'},
{'id':3,'product_id':30,'price':20,'quantity':4, 'name':'product_3'},
]
由于♥
您需要根据公共键(例如product_id)对字典进行分组。这可以通过将字典列表转换为字典的字典来实现。然后在组中每个惟一的字典实例中组合可添加的键。
aList= [
{'id':1,'product_id':20,'price':50,'quantity':1, 'name':'product_2'},
{'id':2,'product_id':20,'price':50,'quantity':1, 'name':'product_2'},
{'id':3,'product_id':30,'price':20,'quantity':4, 'name':'product_3'},
]
groups = dict() # product_id:dictionary
for d in aList:
group = groups.setdefault(d["product_id"],d) # add/get first occurrence
if group is not d:
group["price"] += d["price"] # combine additive fields
group["quantity"] += d["quantity"] # for duplicates
aList = list(groups.values()) # convert groups back to a list
print(aList)
[{'id': 1, 'product_id': 20, 'price': 100, 'quantity': 2, 'name': 'product_2'},
{'id': 3, 'product_id': 30, 'price': 20, 'quantity': 4, 'name': 'product_3'}]