我需要帮助。
我有一个列表o dict:
[{"title": "Report 1", "value": 1000, "commission": 2000, "user": "user_1"},
{"title": "Report 2", "value": 500, "commission": 300, "user": "user_1"},
{"title": "Report 3", "value": 1500, "commission": 300, "user": "user_2"}]
我需要对数值求和,并按用户分组和每个用户的总报告
[{"value": 1500, "commission": 2300, "user": "user_1", "total": 2},
{"value": 1500, "commission": 300, "user": "user_2", "total": 1}]
OBS:在纯python中
答案 0 :(得分:2)
使用非常简单的迭代方法。
<强>演示:强>
data = [{"title": "Report 1", "value": 1000, "commission": 2000, "user": "user_1"},
{"title": "Report 2", "value": 500, "commission": 300, "user": "user_1"},
{"title": "Report 3", "value": 1500, "commission": 300, "user": "user_2"}]
d = {}
for i in data:
if i['user'] not in d:
d[i["user"]] = {"value": i["value"], "commission": i["commission"], "user": i['user'], "total": 1}
else:
d[i["user"]]["value"] += i["value"]
d[i["user"]]["commission"] += i["commission"]
d[i["user"]]["total"] += 1
print(d.values())
<强>输出:强>
[{'commission': 300, 'total': 1, 'user': 'user_2', 'value': 1500}, {'commission': 2300, 'total': 2, 'user': 'user_1', 'value': 1500}]