【问题标题】:Sum and count list of dict in pure python [closed]纯python中dict的总和和计数列表[关闭]
【发布时间】:2018-05-17 15:56:20
【问题描述】:

我需要帮助。

我有一个字典列表:

[{"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中

【问题讨论】:

  • 请先尝试一下,我们才能帮您调试
  • 这个问题非常清楚,包含回答问题所需的所有信息。此外,如果用户不了解功能如何工作的基础知识,如果目标是提出高质量的问题,则不应强迫用户提供尝试。因此,cmets 和 hold 似乎不合适。

标签: python python-2.7 list dictionary


【解决方案1】:

使用非常简单的迭代方法。

演示:

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

【讨论】:

    猜你喜欢
    • 2015-07-12
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 2021-04-14
    • 2014-06-12
    相关资源
    最近更新 更多