我正面临字典这个奇怪的问题。我有 2 部词典 source_dict 和 target_dict。source_dict 由它自己的逻辑组成。我正在尝试使用 source_dict 派生 target_dict。下面是我的代码。
来源字典:
{
"t1": {
"t1c": 92074660,
"t1p": 92074660,
"t1l": 0,
"s1": {
"s1c": 1558475,
"s1p": 1558475,
"s1l": 0,
"s1t1": {
"s1t1c": 1558475,
"s1t1p": 1558475,
"s1t1l": 0
}
},
"s2": {
"s2c": 4439058,
"s2p": 4439058,
"s2l": 0,
"s2t1": {
"s2t1c": 83946,
"s2t1p": 83946,
"s2t1l": 0
},
"s2t2": {
"s2t2c": 4355112,
"s2t2p": 4355112,
"s2t2l": 0
}
}
}
}
预期的 target_dict :
{
"c": 5341515,
"p": 5341515,
"l": 0,
"s1": {
"s1c": 5341515,
"s1p": 5341515,
"s1l": 0,
"s1t1": {
"s1t1c": 5341515,
"s1t1p": 5341515,
"s1t1l": 0
}
}
}
算术计算:
c = source_dict(t1.t1c + t2.t2c + t3.t3c)
s1c = source_dict(t1.s1.s1c + t2.s1.s1c + t3.s1.s1c)
我的逻辑:
for k, v in source_dict.items():
for s, offset in v.items():
if isinstance(offset, dict):
for tpc, val in offset.items():
if 'c' not in tpc and 'p' not in tpc and 'l' not in tpc:
if tpc not in target_dict[s].keys():
target_dict[s][tpc] = val
else:
target_dict[s][tpc]['c'] = target_dict[s][tpc]['c'] + val['c']
target_dict[s][tpc]['p'] = target_dict[s][tpc]['p'] + val['p']
target_dict[s][tpc]['l'] = target_dict[s][tpc]['l'] + val['l']
问题:使用此逻辑,它也在更新 source_dict 中的值。我可以得到一些帮助来理解到底是什么地方出了问题,这使得 source_dict 得到新计算值的更新吗?
慕容森
相关分类