如何对dict列表中的值求和,并将其设置为新键



我在这里遇到了一些问题,我希望这里的人能帮助我解决这个问题

我有dict 的清单

user_data = [{'name':'SAL-001':'amount':1000},
{'name':'SAL-001':'amount':2000},
{'name':'SAL-002':'amount':1000},
{'name':'SAL-003':'amount':1000},
{'name':'SAL-003':'amount':1000},
{'name':'SAL-003':'amount':2000}]

我想把具有相同id的dict列表中的金额相加,并把它放在新的密钥total_amount中,就像这个一样

output = [{'name':'SAL-001','amount':1000,'total_amount': 1000},
{'name':'SAL-001','amount':2000,'total_amount': 3000},
{'name':'SAL-002','amount':1000,'total_amount': 1000},
{'name':'SAL-003','amount':1000,'total_amount': 1000},
{'name':'SAL-003','amount':1000,'total_amount': 2000},
{'name':'SAL-003','amount':2000,'total_amount': 4000}]

我怎样才能达到这样的效果?有人能帮我吗?

我很感激你的回答谢谢

下面的代码是考虑到数据按名称排序而编写的

user_data = [{'name':'SAL-001','amount':1000},
{'name':'SAL-001','amount':2000},
{'name':'SAL-002','amount':1000},
{'name':'SAL-003','amount':1000},
{'name':'SAL-003','amount':1000},
{'name':'SAL-003','amount':2000}]
# First total_amount is set to it's amount
user_data[0]['total_amount']=user_data[0]['amount']
for user in range(1,len(user_data)):
#we check whether we need to add the amount to the total amount
# if the name is same we add current amount to the previous total amount
if user_data[user]['name']==user_data[user-1]['name']:
user_data[user]['total_amount']=user_data[user-1]['total_amount']+user_data[user]['amount']
#if the name is different we initialize total amount to the current amount
else:
user_data[user]['total_amount']=user_data[user]['amount']
print(user_data)

如果有任何更改/修改,或者如果有更好的方法,请告诉我

最新更新