Python dictionary copy() 方法用于返回当前字典的浅表副本。对象的浅表副本是指其属性与从中创建副本的源对象的属性相同的副本,共享相同的引用 (指向相同的基础值)。简而言之,将创建一个新词典,其中原始词典中的引用填充了一个副本。
我们还可以使用 = 运算符复制字典,该运算符指向与原始对象相同的对象。因此,如果对复制的词典进行了任何更改,它也会反映在原始词典中。简而言之,将创建对原始词典的新引用。
语法
以下是 Python dictionary copy() 方法的语法 -
参数
此方法不接受任何参数。
返回值
此方法返回当前词典的浅表副本。
例以下示例显示了 Python dictionary copy() 方法的用法。在这里,我们将创建一个字典 'dict_1',然后创建它的副本。
当我们运行上述程序时,它会产生以下结果——
New Dictionary : {'Name': 'Zara', 'Age': 7}
例
现在,我们正在更新第二个字典的元素。此后,检查更改是否反映在第一个字典中。
以下是上述代码的输出 -
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]}
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'。然后创建原始词典的浅表副本。之后,将元素添加到浅表副本中。此后,检索结果显示元素被附加到字典的浅表副本,而原始字典保持不变。
上述代码的输出如下 -
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'}
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'}