0

I got something annoying going on in Python, I created a dictionary and then created a second one that takes the same keys and values from the first one, but when I modify the first dictionary the second one also changes, why is that?

Example:

testblock = {
    0:1, 1:2, 2:3, 3:4,
    4:5, 5:6, 6:7, 7:8,
    8:9, 9:10, 10:0, 11:11,
    12:13, 13:14, 14:15, 15:12}
t2 = testblock
testblock[2] = 10

testblock would be the first dictionary and t2 the second one, it happens even if I declare several dictionaries identical to testblock, like a t3, t4 etc When I call them, they all show the same changes I did with testblock

1 Answers1

1

It's because both t2 and t1 are referring to same dictionary object underneath. To verify that run id(t2) and run id(t1) on python interpreter. Both will return same value. For more info. refer to python model in python docs.

Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97