Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 向目标字典中的现有键添加数值也会更新源字典_Python_Dictionary - Fatal编程技术网

Python 向目标字典中的现有键添加数值也会更新源字典

Python 向目标字典中的现有键添加数值也会更新源字典,python,dictionary,Python,Dictionary,我正面临着一个关于字典的奇怪问题。我有两个字典源字典和目标字典。源字典有自己的逻辑。我正在尝试使用源代码派生目标代码。下面是我的代码 资料来源: { "t1": { "t1c": 92074660, "t1p": 92074660, "t1l": 0, "s1": { "s1c": 1558475, "s

我正面临着一个关于字典的奇怪问题。我有两个字典源字典和目标字典。源字典有自己的逻辑。我正在尝试使用源代码派生目标代码。下面是我的代码

资料来源:

  {
  "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
      }
    }
  }
}
预期目标:

 {
  "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']

问题:使用此逻辑,它也在更新源目录中的值。我能得到一些帮助来理解到底是什么原因导致源代码使用新的计算值进行更新吗?

虽然将源代码指定给目标代码的位置不太明显,但我猜python处理变量的条件是相同的(尤其是
dict
str
\uuuuuuuuuuuuuuuuuuuuuuu
)作为指针仍然适用。您只需对源词典进行
deepcopy
。检查此链接以获得更好的说明