Python 字典 copy() 方法



Python 字典 copy() 方法用於返回當前字典的淺複製。物件的淺複製是指其屬性與從中建立複製的源物件相同,共享相同的引用(指向相同的基礎值)。簡而言之,建立一個新的字典,其中原始字典的引用被複制填充。

我們還可以使用=運算子複製字典,它指向與原始字典相同的物件。因此,如果對複製的字典進行任何更改,也會反映在原始字典中。簡而言之,為原始字典建立了一個新的引用。

語法

以下是Python 字典 copy() 方法的語法:

dict.copy()

引數

此方法不接受任何引數。

返回值

此方法返回當前字典的淺複製。

示例

以下示例顯示了 Python 字典 copy() 方法的使用。這裡我們建立了一個字典 'dict_1',然後建立了它的一個副本。

dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = dict1.copy()
print ("New Dictionary : %s" %  str(dict2))

當我們執行上面的程式時,它會產生以下結果:

New Dictionary : {'Name': 'Zara', 'Age': 7}

示例

現在,我們正在更新第二個字典的元素。然後,檢查更改是否反映在第一個字典中。

dictionary = {5: 'x', 15: 'y', 25: [7, 8, 9]}
print("The given dictionary is: ", dictionary)
# using copy() method to copy
d2 = dictionary.copy()
print("The new copied dictionary is: ", d2)
# Updating the elements in second dictionary
d2[15] = 2
# updating the items in the list 
d2[25][1] = '98' 
print("The updated dictionary is: ", d2)

以下是上述程式碼的輸出:

The given dictionary is:  {5: 'x', 15: 'y', 25: [7, 8, 9]}
The new copied dictionary is:  {5: 'x', 15: 'y', 25: [7, 8, 9]}
The updated dictionary is:  {5: 'x', 15: 2, 25: [7, '98', 9]}

示例

在下面的程式碼中,我們建立了一個字典 'dict_1'。然後建立原始字典的淺複製。之後,向淺複製中添加了一個元素。然後,檢索結果,顯示元素被追加到字典的淺複製中,而原始字典保持不變。

# Creating a dictionary
dict_1 = {"1": "Lion", "2": "Tiger"}
print("The first dictionary is: ", dict_1)
# Create a shallow copy of the first dictionary
SC = dict_1.copy()
print("The shallow copy of the dictionary is: ", SC)
# Append an element to the created shallow copy
SC[3] = "Cheetah"
print("The shallow copy after adding an element is: ", SC)
# No changes in the first dictionary
print("There is no changes in the first dictionary: ", dict_1)

上述程式碼的輸出如下:

The first dictionary is:  {'1': 'Lion', '2': 'Tiger'}
The shallow copy of the dictionary is:  {'1': 'Lion', '2': 'Tiger'}
The shallow copy after adding an element is:  {'1': 'Lion', '2': 'Tiger', 3: 'Cheetah'}
There is no changes in the first dictionary:  {'1': 'Lion', '2': 'Tiger'}
python_dictionary.htm
廣告