0

For some reason when I modify mydict2 it changes the contents of mydict

Here is my code:

mydict = {1:'a', 2:'b'}
mydict2 = mydict
mydict2[1] = 'c'
print(mydict2)

If you try this, it outputs {1: 'c', 2: 'b'}

It should output {1: 'a', 2: 'b'} and when you do print(mydict) it should output {1: 'c', 2: 'b'}

Rlz
  • 1,649
  • 2
  • 13
  • 36

5 Answers5

1

mydict and mydict2 are both references to the same object.

So changes to mydict or mydict2 will change the same object, and therefore it looks like changing one of them is changing the other.

MxLDevs
  • 19,048
  • 36
  • 123
  • 194
1

mydict and mydict2 are both pointing to the same object in memory. When either one changes, the other does as well. They references to the same dictionary.

It is not enough to use the assignment operator to make a proper copy. If you want mydict2 to point to a copy of the dictionary mydict points to, you need to tell Python to explicitly make a copy:

>>> mydict = {1:'a', 2:'b'}
>>> mydict2 = mydict.copy()
>>> mydict2[1] = 'c'
>>> mydict
{1: 'a', 2: 'b'}
>>> mydict2
{1: 'c', 2: 'b'}
>>> 

Note however that this method will fail if you have a nested dictionary structure. You'd need to use copy.deepcopy() in that case.

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
0

You should use function copy:

from copy import copy
mydict = {1:'a', 2:'b'}
mydict2 = copy(mydict)
mydict2[1] = 'c'
print(mydict2)

There are two links for the same object. If you want to have two objects, you should copy your dict

Oleksandr Dashkov
  • 2,249
  • 1
  • 15
  • 29
0

You are setting mydic2 equal to the object mydict. When you mutate mydict2, it will change the contents of mydict1.

Try using copy or copy.deepcopy as seen here: python docs

See this thread for an example: stackoverflow thread

Community
  • 1
  • 1
M. Urban
  • 11
  • 1
0

mydict and mydict2 both reference the same dictionary, so when you change one, you change the other one too.

TMW6315
  • 43
  • 9