use*_*044 2 python dictionary python-2.7
为什么使用该dict()函数不会像标准键:值对字典那样创建带有嵌套字典的副本?
字典
A = {'key' : 'value'}
B = dict(A)
A['key'] = 10
print A, B
Run Code Online (Sandbox Code Playgroud)
输出:
{'key': 10} {'key': 'value'}
Run Code Online (Sandbox Code Playgroud)
嵌套字典:
A = {'key' : {'subkey' : 'value'}}
B = dict(A)
A['key']['subkey'] = 10
print A, B
Run Code Online (Sandbox Code Playgroud)
输出:
{'key': {'subkey': 10}} {'key': {'subkey': 10}}
Run Code Online (Sandbox Code Playgroud)
您需要进行深度复制:
from copy import deepcopy
A = {'key' : {'subkey' : 'value'}}
B = deepcopy(A)
A['key']['subkey'] = 10
print(A, B)
# {'key': {'subkey': 10}} {'key': {'subkey': 'value'}}
Run Code Online (Sandbox Code Playgroud)