当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Dictionary copy()用法及代码示例


他们使用copy()方法返回字典的浅拷贝。

用法:

dict.copy()

参数:


The copy() method doesn't take any parameters.

返回值:

This method doesn't modify the original
dictionary just returns copy of the dictionary.

例子:

Input:original = {1:'geeks', 2:'for'}
        new = original.copy()
Output:original: {1:'one', 2:'two'}
         new: {1:'one', 2:'two'}

错误:

As we are not passing any parameters 
there is no chance of any error.
# Python program to demonstrate working 
# of dictionary copy 
original = {1:'geeks', 2:'for'} 
  
# copying using copy() function 
new = original.copy() 
  
# removing all elements from the list 
# Only new list becomes empty as copy() 
# does shallow copy. 
new.clear() 
  
print('new:', new) 
print('original:', original)

输出:

new: {}
original: {1:'geeks', 2:'for'}

与简单分配“=”有何不同?
与copy()不同,赋值运算符执行深层复制。

# Python program to demonstrate difference 
# between = and copy() 
original = {1:'geeks', 2:'for'} 
  
# copying using copy() function 
new = original.copy() 
  
# removing all elements from new list 
# and printing both 
new.clear() 
print('new:', new) 
print('original:', original) 
  
original = {1:'one', 2:'two'} 
  
# copying using = 
new = original 
  
# removing all elements from new list 
# and printing both 
new.clear() 
print('new:', new) 
print('original:', original)

输出:

new: {}
original: {1:'geeks', 2:'for'}
new: {}
original: {}


相关用法


注:本文由纯净天空筛选整理自pawan_asipu大神的英文原创作品 Python Dictionary copy()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。