-2

This is my sample code:

dict1 = {'a': 5, 'b': 6, 'c': 7}
dict2 = dict1
for i in dict1:
    dict1[i] += 5
print dict1
print dict2

Output looks like this:

{'a': 10, 'c': 12, 'b': 11}
{'a': 10, 'c': 12, 'b': 11}

Why is dict2 changing without me telling it to?

Python 2.7.10 on GCC 4.8.2 Linux.

Also tried on 2.7.12 on GCC 5.4.0, same result.

Tristan Price
  • 663
  • 6
  • 7

1 Answers1

0

When you write dict2 = dict1, you are not creating the copy of dict1, you just set dict2 as a pointer to the dict1 dictionary. So if you change dict1, dict2 will be changed too because it looks at the same dictionary in memory. If you want to copy dict1 to dict2, you should use deepcopy function from the copy module from the Python standard library.

vurmux
  • 9,420
  • 3
  • 25
  • 45