1

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
  • 7,943
  • 23
  • 91
  • 154

1 Answers1

4

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
  • 40,483
  • 12
  • 109
  • 137
Padraic Cunningham
  • 168,988
  • 22
  • 228
  • 312