创建嵌套字典的副本而不是引用

时间:2015-04-24 18:46:05

标签: python python-2.7 dictionary

为什么使用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}}

1 个答案:

答案 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'}}