0

I'm facing this weird problem with dictionary. I have 2 dictionaries source_dict and target_dict. source_dict is formed with its own logic. I'm trying to derive target_dict using source_dict. Below is my code.

source_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
      }
    }
  }
}

expected target_dict :

 {
  "c": 5341515,
  "p": 5341515,
  "l": 0,
  "s1": {
    "s1c": 5341515,
    "s1p": 5341515,
    "s1l": 0,
    "s1t1": {
      "s1t1c": 5341515,
      "s1t1p": 5341515,
      "s1t1l": 0
    }
  }
}

Arithmetic Calculation :

c = source_dict(t1.t1c + t2.t2c + t3.t3c)
s1c = source_dict(t1.s1.s1c + t2.s1.s1c + t3.s1.s1c)

My Logic :

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

Issue : With this logic it is updating the values in source_dict too. Can I get some help in understanding what exactly is going wrong which is making source_dict to get updated with new calculated values?

Ashwin
  • 439
  • 1
  • 7
  • 23

1 Answers1

1

While it’s not so obvious where you assigned source_dict to target_dict, I guess the same condition of python treating variables (especially dict or str or __builtins__) as pointers still applies. You only need to make a deepcopy of the source dictionary. Check this link for better clarification https://stackoverflow.com/a/2466752/1836069

Olasimbo
  • 965
  • 6
  • 14