Python Dictionary copy()
They copy() method returns a shallow copy of the dictionary.
Syntax:
dict.copy()
Parameters:
The copy() method doesn't take any parameters.
Returns:
This method doesn't modify the original dictionary just returns copy of the dictionary.
Examples:
Input : original = {1:'geeks', 2:'for'}
new = original.copy()
Output : original: {1: 'one', 2: 'two'}
new: {1: 'one', 2: 'two'}
Error:
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) |
chevron_right
filter_none
Output:
new: {}
original: {1: 'geeks', 2: 'for'}
How is it different from simple assignment “=”?
Unlike copy(), the assignment operator does deep 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) |
chevron_right
filter_none
Output:
new: {}
original: {1: 'geeks', 2: 'for'}
new: {}
original: {}
Recommended Posts:
- Python | Ways to Copy Dictionary
- copy in Python (Deep Copy and Shallow Copy)
- Python | Convert flattened dictionary into nested dictionary
- Python | Convert nested dictionary into flattened dictionary
- Python | Convert string dictionary to dictionary
- Python | Pretty Print a dictionary with dictionary value
- set copy() in python
- Python PIL | copy() method
- Python | shutil.copy() method
- Python | Pandas TimedeltaIndex.copy
- Python | Pandas Index.copy()
- Python | Numpy matrix.copy()
- Python | How to copy a nested list
- Python list | copy() method
- numpy.ndarray.copy() in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




