Python 字典 copy() 方法



Python 字典 copy() 方法用于返回当前字典的浅拷贝。对象的浅拷贝是指其属性与从中创建拷贝的源对象相同,共享相同的引用(指向相同的基础值)。简而言之,创建一个新的字典,其中原始字典的引用被复制填充。

我们还可以使用=运算符复制字典,它指向与原始字典相同的对象。因此,如果对复制的字典进行任何更改,也会反映在原始字典中。简而言之,为原始字典创建了一个新的引用。

语法

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

dict.copy()

参数

此方法不接受任何参数。

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

返回值

此方法返回当前字典的浅拷贝。

示例

以下示例显示了 Python 字典 copy() 方法的使用。这里我们创建了一个字典 'dict_1',然后创建了它的一个副本。

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

当我们运行上面的程序时,它会产生以下结果:

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

示例

现在,我们正在更新第二个字典的元素。然后,检查更改是否反映在第一个字典中。

Open Compiler
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'。然后创建原始字典的浅拷贝。之后,向浅拷贝中添加了一个元素。然后,检索结果,显示元素被追加到字典的浅拷贝中,而原始字典保持不变。

Open Compiler
# 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
广告