他們使用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: {}
相關用法
- Python set copy()用法及代碼示例
- Python PIL copy()用法及代碼示例
- Python Numpy matrix.copy()用法及代碼示例
- Python Pandas Index.copy()用法及代碼示例
- Python list copy()用法及代碼示例
- Python Pandas TimedeltaIndex.copy用法及代碼示例
注:本文由純淨天空篩選整理自pawan_asipu大神的英文原創作品 Python Dictionary copy()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。