-2

In the code below e is my dictionary . ee is the shallow copy of my dictionary created by using the copy method.

e = {'a': 100, 'b': [1, 2]}
ee = e.copy()

After the first statement below, the value in ee also changes .

e['b'][0] = 'foo'  # {'a': 100, 'b': ['foo', 2]}

After the below statement, the value in ee does not change.

e['a'] = 300     # {'a': 100, 'b': ['foo', 2]}

Can anyone explain the reason for the same or provide link to the question if it is already addressed.

1 Answers1

0

As you mentioned, this is a shallow copy. In order to create an "independent" copy, use:

from copy import deepcopy
ee = deepcopy(e)

Now you can change e without affecting ee

Gabio
  • 9,126
  • 3
  • 12
  • 32