Q:

Python: Dictionary changing

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

A:

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.

