【发布时间】:2020-03-18 14:18:21
【问题描述】:
我搜索了一段时间,但找不到解决问题的确切方法。我有一个格式的字典列表:
d = [{"sender": "a", "time": 123, "receiver": "b", "amount": 2}, {"sender": "c", "time": 124, "receiver": "b", "amount": 10}, {"sender": "a", "time": 130, "receiver": "b", "amount": 5}]
我想找到迭代所有字典并计算给定的发送者-接收者对出现的次数以及总数的最佳方法。
所以我想得到:
result = [{"sender": "a", "receiver":b, "count": 2, "total_amount":7}, {"sender": "c", "receiver":b, "count": 1, "total_amount":10}]
我很确定我可以通过逐个迭代列表中的所有字典来完成这项工作,将信息保存在临时字典中,但这会导致大量嵌套 if 循环。我希望有一种更清洁的方法来做到这一点。
我知道我可以使用Counter 来计算唯一值的出现次数:
from collections import Counter
Counter(val["sender"] for val in d)
这会给我:
>>> ({"a":2, "c":1})
但我怎样才能为一对值执行此操作并为每个值分别设置字典?
提前谢谢你,我希望我的问题足够清楚
【问题讨论】:
标签: python dictionary