2

Why is it that using the dict() function does not create a copy with a nested dictionary as it does for a standard key:value pair dictionary?

Dictionary

A = {'key' : 'value'}
B = dict(A)
A['key'] = 10
print A, B

Output:

{'key': 10} {'key': 'value'}

Nested Dictionary:

A = {'key' : {'subkey' : 'value'}}
B = dict(A)
A['key']['subkey'] = 10
print A, B

Output:

{'key': {'subkey': 10}} {'key': {'subkey': 10}}
user2242044
  • 8,803
  • 25
  • 97
  • 164

1 Answers1

5

You need to make a deepcopy:

from copy import deepcopy
A = {'key' : {'subkey' : 'value'}}
B = deepcopy(A)
A['key']['subkey'] = 10
print(A, B)
# {'key': {'subkey': 10}} {'key': {'subkey': 'value'}}
vaultah
  • 44,105
  • 12
  • 114
  • 143
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321