English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The copy() method returns a shallow copy of the dictionary.
The syntax of copy() is:
dict.copy()
The copy() method has no parameters.
This method returns a shallow copy of the dictionary. It does not modify the original dictionary.
original = {1: 'one', 2: 'two'} new = original.copy() print('Original dictionary: ', original) print('Copy dictionary: ', new)
When running the program, the output is:
Original dictionary: {1: 'one', 2: 'two'} Copy dictionary: {1: 'one', 2: 'two'}
When using the copy() method, a new dictionary will be created, which will fill with the copies of the references in the original dictionary.
When using the = operator, a new reference to the original dictionary will be created.
original = {1: 'one', 2: 'two'} new = original # Delete all elements from the list new.clear() print('new: ', new) print('original: ', original)
When running the program, the output is:
new: {} original: {
Here, when the 'new' dictionary is cleared, the 'original' dictionary is also cleared.
original = {1: 'one', 2: 'two'} new = original.copy() # Delete all elements from the list new.clear() print('new: ', new) print('original: ', original)
When running the program, the output is:
new: {} original: {1: 'one', 2: 'two'}
Here, the 'new' dictionary is cleared, but the 'original' dictionary remains unchanged.