纯Python中dict的总和计数列表

时间:2018-05-17 15:56:21

标签: python python-2.7 list dictionary

我需要帮助。

我有一个列表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中

1 个答案:

答案 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}]