为什么使用dict()
函数不会像使用标准键:值对词典那样创建嵌套字典的副本?
词典
A = {'key' : 'value'}
B = dict(A)
A['key'] = 10
print A, B
输出:
{'key': 10} {'key': 'value'}
嵌套字典:
A = {'key' : {'subkey' : 'value'}}
B = dict(A)
A['key']['subkey'] = 10
print A, B
输出:
{'key': {'subkey': 10}} {'key': {'subkey': 10}}
答案 0 :(得分:2)
您需要制作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'}}