Python Dictionary copy() 函数用法

2023-09-17 22:25:37

dict.copy() 方法返回字典的浅表副本。

也可以使用 = 运算符复制字典,该运算符指向与原始对象相同的对象。因此,如果在复制的词典中进行任何更改,也将反映在原始词典中。

语法:

dict.copy()

参数:

无参数。

返回类型:

返回字典的浅表副本。

下面的示例演示 dict.copy() 方法。

romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
newRomanNums = romanNums.copy()
print("Original dictionary: ",romanNums)
print("Copied dictionary: ",newRomanNums)

输出:

Original dictionary:  {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5}
Copied dictionary:  {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5}

通过 copy() 方法复制字典时,在新字典中所做的任何更改都不会反映在原始字典中。

romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
newRomanNums = romanNums.copy()
del newRomanNums['V'] # deleting 'V'
print("Original dictionary: ",romanNums)
print("Copied dictionary: ",newRomanNums)

输出:

Original dictionary:  {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5}
Copied dictionary:  {'I': 1, 'II': 2, 'III': 3, 'IV': 4}

当使用=运算符复制字典时,复制字典中的任何更改都将反映在原始字典中,反之亦然。

romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
newRomanNums = romanNums
newRomanNums.clear()
print("Original dictionary: ",romanNums)
print("Copied dictionary: ",newRomanNums)

输出:

Original dictionary:  {}
Copied dictionary:  {}