我正在编写一个程序,帮助整理来自多个来源的数据以进行分析。
我目前有一本看起来像这样的字典:
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},
},
}
},
},
},
到目前为止,我有非整体词典中的盈亏数据。
我想做的是有一个函数来填充总体总额、利润和损失。为此,我们假设利润和损失相加,因此利润 1 和损失 1 总计为 2。
通过查看一些类似的问题和一些思考,我有以下几点:
def calculateOveralls(dictionary, query):
for a in dictionary[query]: #A.B,C
for b in dictionary[query][a]: #Sub A, Sub B, Sub C
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]
任何帮助将不胜感激。
非常感谢!
我猜这是您想要实现的输出的函数:
def calculate_overalls(data, query):
for sec in data[query]: # A, B etc
all_profit = {"q1": 0, "q2": 0, "q3": 0, "q4": 0}
all_loss = {"q1": 0, "q2": 0, "q3": 0, "q4": 0}
all_total = {"q1": 0, "q2": 0, "q3": 0, "q4": 0}
for sub_sec in data[query][sec]: # Sub A, Sub B etc
if sub_sec == "overall":
continue
for q in ["q1", "q2", "q3", "q4"]:
profit = data[query][sec][sub_sec]["Profit"][q]
loss = data[query][sec][sub_sec]["Loss"][q]
total = profit + loss
# Add all to overall
all_profit[q] += profit
all_loss[q] += loss
all_total[q] += total
data[query][sec]["overall"]["Profit"] = all_profit
data[query][sec]["overall"]["Loss"] = all_loss
data[query][sec]["overall"]["total"] = all_total
output = {...}
calculate_overalls(output, "main")
print(output)
或者,如果您遇到不需要的结果,请评论错误的估计部分)