Python Dictionary copy() method “returns a copy (shallow copy) of the dictionary.”
Syntax
dictionary.copy()
Parameters
The copy() method does not take any arguments.
Return value
It returns a shallow copy of the dictionary. It doesn’t modify the original dictionary.
Visual Representation
Example 1: How does the Dictionary copy() Method work?
appDict = {
'shopping': 'flipkart',
'transport': 'ola',
'banking': 'paytm',
'hotel': 'oyo rooms'
}
print("Original Dictionary", appDict)
secDict = appDict.copy()
print("Copied Dictionary: ", secDict)
Output
Original Dictionary {'shopping': 'flipkart', 'transport': 'ola',
'banking': 'paytm', 'hotel': 'oyo rooms'}
Copied Dictionary: {'shopping': 'flipkart', 'transport': 'ola',
'banking': 'paytm', 'hotel': 'oyo rooms'}
In the above example, an exact copy of appDict is created and assigned to the secDict.
Let’s modify the copied dictionary and see if it changes the original dictionary as well.
origDict = {
'shopping': 'flipkart',
'transport': 'ola',
'banking': 'paytm',
'hotel': 'oyo rooms'
}
copyDict = origDict.copy()
print(copyDict)
origDict.clear()
print(copyDict)
Here, we created a copy of the Dictionary and cleared the original dictionary to see if the copied Dictionary was emptied.
Output
{'shopping': 'flipkart', 'transport': 'ola', 'banking': 'paytm', 'hotel': 'oyo rooms'}
{'shopping': 'flipkart', 'transport': 'ola', 'banking': 'paytm', 'hotel': 'oyo rooms'}
Example 2: Using = Operator to Copy Dictionaries
data = {"a":'homer', "b":'simpson'}
new = data
new.clear()
print('new: ', new)
print('data: ', data)
Output
new: {}
data: {}
The assignment operator will modify the original dictionary if you change the copied dictionary because the assignment operator creates a reference to the original dictionary.
Example 3: Python Dictionary copy() and update
data = {"a":'homer', "b":'simpson'}
print("Original dict: ", data)
dict2 = data.copy()
print("New copy:", dict2)
dict2["a"] = 'bart'
print("Updated copy:", dict2)
Output
Original dict: {'a': 'homer', 'b': 'simpson'}
New copy: {'a': 'homer', 'b': 'simpson'}
Updated copy: {'a': 'bart', 'b': 'simpson'}
That’s it.