Python 複製字典
複製字典
您不能簡單地透過鍵入 dict2 = dict1
來複制字典,因為: dict2
將僅僅是 dict1
的一個引用,在 dict1
中所做的更改也會自動應用到 dict2
中。
有幾種方法可以進行復制,一種方法是使用內建的字典方法 copy()
。
示例
使用 copy()
方法複製字典
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
自己動手試一試 »
另一種複製方法是使用內建的 dict()
方法。
示例
使用 dict()
方法複製字典
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
自己動手試一試 »