Python嵌套字典求和:如何填充overall节点的汇总数据
多源数据整理程序的字典填充问题
我正在开发一个用于整合多源数据做分析的程序,目前有如下嵌套结构的字典:
output = { "main": { "overall": { "overall": { "total": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, "Profit": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, "Loss": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, }, "Sub A": { "total": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, "Profit": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, "Loss": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, }, "Sub B": { "total": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, "Profit": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, "Loss": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, }, }, "A": { "overall": { "total": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, "Profit": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, "Loss": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, }, "Sub A": { "total": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, "Profit": {"q1": 10,"q2": 8,"q3": 19,"q4": 7}, "Loss": {"q1": 4,"q2": 2,"q3": 6,"q4": 10}, }, "Sub B": { "total": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, "Profit": {"q1": 50,"q2": 70,"q3": 54,"q4": 77}, "Loss": {"q1": 2,"q2": 8,"q3": 5,"q4": 40}, }, }, "B": { "overall": { "total": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, "Profit": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, "Loss": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, }, "Sub A": { "total": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, "Profit": {"q1": 75,"q2": 23,"q3": 25,"q4": 12}, "Loss": {"q1": 64,"q2": 22,"q3": 12,"q4": 5}, }, "Sub B": { "total": {"q1": 0,"q2": 0,"q3": 0,"q4": 0}, "Profit": {"q1": 65,"q2": 53,"q3": 3,"q4": 5}, "Loss": {"q1": 10,"q2": 12,"q3": 1,"q4": 2}, }, } } }
目前非overall节点的Profit和Loss已有数据,需要编写函数完成以下填充:
- 所有节点的
total:对应季度的Profit与Loss之和 - 所有
overall节点的Profit:对应层级下所有Sub节点同季度Profit的累加值 - 所有
overall节点的Loss:对应层级下所有Sub节点同季度Loss的累加值
我参考相关问题写出了如下函数,希望得到完善建议:
def calculateOveralls(dictionary, query): for a in dictionary[query]: #A,B,overall for b in dictionary[query][a]: #Sub A, Sub B, overall if b == "overall": pass else: for c in dictionary[query][a][b]: # Profit/Loss if c == "total": pass else: for d in dictionary[query][a][b][c]: # quarters dictionary[query][a][b]["total"][d] = dictionary[query][a][b]["total"][d] + dictionary[query][a][b][c][d]
内容的提问来源于stack exchange,提问作者TIC-FLY
相关产品推荐
相关产品推荐

