-2

I have a variable.Then i assign variable to 2nd variable. When i change 2nd variable 1st variable is changed automatically. But i want to change 2nd variable only.

a={'a':1, 'b':2}
b=a

b.update({'x':78})

print(a,'\n===========================\n', b)
Jmonsky
  • 1,519
  • 1
  • 9
  • 16
Vagif
  • 49
  • 1
  • 6

2 Answers2

2

So you are not creating a copy, but a reference.

Use the dictionaries .copy() method method to get a copy

a = {'a':1, 'b':2}
b = a.copy()
Jmonsky
  • 1,519
  • 1
  • 9
  • 16
0

As explained above, you did a reference and not a copy. In your case a and b have the same address in memory. Hence, update a or b is the same.

Here an explanation about the difference between these two concepts.

damdamo
  • 331
  • 2
  • 10