2015-04-24 67 views
0

爲什麼使用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}} 

回答

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