-2

I am trying to create 2 child dictionary from parent dictionary , but if performing any del operation it is impacting other child

For example :

My parent dictionary is mentioned below

p : { 2:10 , 4:20 , 5:35 }

My child dictionary which is nothing but copy of main

child_1 = p.copy()
child_2 = p.copy()

If I am performing any delete operation on child_1 then other child_2 is getting impacted It should not happen.

del  child_1[2]

It as deleted form child_2 as well that key,value of above

I want both should not be impacting each other if any del is performing

nodehep223
  • 43
  • 6

3 Answers3

-1

You should use deepcopy() instead of copy().

Explaination : copy() create a new object, but for mutable objects, it fill elements by creating references to parent's elements. deepcopy() will create a new object then recursively create copy of parent's elements.

Léo Beaucourt
  • 257
  • 2
  • 6
-1

There is another question beforehand, that will help you.

You can use this Link.

I prefer:

import copy
dict2 = copy.deepcopy(dict1)

or

dict2 = dict(dict1)

or

dict2 = dict1.copy()
S.Shakeri
  • 7
  • 1
  • 3
-2

You can loop over the parent dictionary's keys to copy it one-by-one:

child_1 = {}
child_2 = {}
for key in p.keys():
    child_1[key] = p[key]
    child_2[key] = p[key]
Schnitte
  • 1,193
  • 4
  • 16