Python Dictionary copy() method returns a shallow copy of the dictionary. let’s see the Python Dictionary copy() method with examples:
Examples
Input: original = {1:'geeks', 2:'for'}
new = original.copy() // Operation
Output: original: {1: 'one', 2: 'two'}
new: {1: 'one', 2: 'two'}
Syntax of copy() method
Syntax: dict.copy()
Return: This method doesn’t modify the original, dictionary just returns copy of the dictionary.
Python Dictionary copy() Error:
As we are not passing any parameters, there is no chance of any error.
Example 1: Examples of Python Dictionary copy()
Python program to demonstrate the working of dictionary copy.
Python3
original = { 1 : 'geeks' , 2 : 'for' }
new = original.copy()
new.clear()
print ( 'new: ' , new)
print ( 'original: ' , original)
|
Output:
new: {}
original: {1: 'geeks', 2: 'for'}
Example 2: Python Dictionary copy() and update
Python program to demonstrate the working of dictionary copy. i.e. Updating dict2 elements and checking the change in dict1.
Python3
dict1 = { 10 : 'a' , 20 : [ 1 , 2 , 3 ], 30 : 'c' }
print ( "Given Dictionary:" , dict1)
dict2 = dict1.copy()
print ( "New copy:" , dict2)
dict2[ 10 ] = 10
dict2[ 20 ][ 2 ] = '45'
print ( "Updated copy:" , dict2)
|
Output:
Given Dictionary: {10: 'a', 20: [1, 2, 3], 30: 'c'}
New copy: {10: 'a', 20: [1, 2, 3], 30: 'c'}
Updated copy: {10: 10, 20: [1, 2, '45'], 30: 'c'}
Difference between shallow copy and deep copy
It means that any changes made to a copy of the object do not reflect in the original object. In python, this is implemented using “deepcopy()” function. whereas in shallow copy any changes made to a copy of an object do reflect in the original object. In python, this is implemented using the “copy()” function.
Example 1: Using copy()
Unlike copy(), the assignment operator does deep copy.
Python3
original = { 1 : 'geeks' , 2 : 'for' }
new = original.copy()
new.clear()
print ( 'new: ' , new)
print ( 'original: ' , original)
original = { 1 : 'one' , 2 : 'two' }
new = original
new.clear()
print ( 'new: ' , new)
print ( 'original: ' , original)
|
Output:
new: {}
original: {1: 'geeks', 2: 'for'}
new: {}
original: {}
Example 2: Using copy.deepcopy
Unlike deepcopy(), the assignment operator does deep copy.
Python3
import copy
original = { 1 : 'geeks' , 2 : 'for' }
new = copy.deepcopy(original)
new.clear()
print ( 'new: ' , new)
print ( 'original: ' , original)
original = { 1 : 'one' , 2 : 'two' }
new = original
new.clear()
print ( 'new: ' , new)
print ( 'original: ' , original)
|
Output:
new: {}
original: {1: 'geeks', 2: 'for'}
new: {}
original: {}