python 字典賦值、淺拷貝、深拷貝
# 專案開發中,因字典可修改,所以注意拷貝方式
import copy
1. 原字典操作
dict1 = {'user': 'test', 'num': [1, 2, 3]} # 原字典
dict2 = dict1 # 直接賦值
dict3 = dict1.copy() # 淺拷貝,只深拷貝父級目錄
dict4 = copy.deepcopy(dict1) # 深拷貝拷貝,父級目錄,子級目錄全部拷貝(需匯入copy模組)
2. 修改原字典
dict1["user"] = "change"
dict1["num"].remove(1)
print("更改後的字典:", dict1)
print("賦值字典:", dict2)
print("淺拷貝:", dict3)
print("深拷貝:", dict4)
# 輸出結果:
更改後的字典: {'user': 'change', 'num': [2, 3]}
賦值字典: {'user': 'change', 'num': [2, 3]} # 原字典改變, 賦值字典隨之改變
淺拷貝: {'user': 'test', 'num': [2, 3]
深拷貝: {'user': 'test', 'num': [1, 2, 3]} # 原字典改變,深拷貝字典不改變
3. 修改賦值、淺拷貝、深拷貝後的字典
dict2["user"] = "test2"
print(dict1)
# {'user': 'test2', 'num': [1, 2, 3]} # 賦值字典改變,原字典也改變
dict3["num"].remove(3)
print(dict1)
# {'user': 'test2', 'num': [1, 2]} # 淺拷貝字典改變,原字典隨之改變
dict4["user"] = "test4"
print(dict1)
# {'user': 'test2', 'num': [1, 2]} # 深拷貝後的字典改變,原字典不改變
總結:
原字典與賦值、淺拷貝之間緊密相連,一方改變,對方隨之改變!
原字典與深拷貝,深拷貝獨立門戶,從此與原字典無關!