2 回答
TA贡献1735条经验 获得超5个赞
可以先构造一个中间字典,然后根据所需的输出对其进行转换:
from collections import defaultdict
q = [
{'ref': '002', 'loc': 'seattle', 'total': '200'},
{'ref': '002', 'loc': 'seattle', 'total': '100'},
{'ref': '123', 'loc': 'dallas', 'total': '100'},
{'ref': '452', 'loc': 'cleveland', 'total': '600'},
{'ref': '123', 'loc': 'dallas', 'total': '200'},
{'ref': '002', 'loc': 'seattle', 'total': '300'}
]
temp_dict = defaultdict(int)
for entry in q:
temp_dict[(entry['ref'], entry['loc'])] += int(entry['total'])
result = [{'ref': k[0], 'loc': k[1], 'total': str(v)} for k, v in temp_dict.items()]
print(result)
# [{'ref': '002', 'loc': 'seattle', 'total': '600'},
# {'ref': '123', 'loc': 'dallas', 'total': '300'},
# {'ref': '452', 'loc': 'cleveland', 'total': '600'}]
TA贡献1810条经验 获得超4个赞
您可以使用一个聚合collections.Counter:
from collections import Counter
from pprint import pprint
q = [
{"ref": "002", "loc": "seattle", "total": "200"},
{"ref": "002", "loc": "seattle", "total": "100"},
{"ref": "123", "loc": "dallas", "total": "100"},
{"ref": "452", "loc": "cleveland", "total": "600"},
{"ref": "123", "loc": "dallas", "total": "200"},
{"ref": "002", "loc": "seattle", "total": "300"},
]
counts = Counter()
for x in q:
ref, loc, total = x["ref"], x["loc"], x["total"]
counts[ref, loc] += int(total)
pprint(
[
{"ref": ref, "loc": loc, "total": str(total)}
for (ref, loc), total in counts.items()
]
)
#[{'loc': 'seattle', 'ref': '002', 'total': '600'},
# {'loc': 'dallas', 'ref': '123', 'total': '300'},
# {'loc': 'cleveland', 'ref': '452', 'total': '600'}]
添加回答
举报