Python Dictionary copy():
The copy() method creates a shallow copy of the dictionary in python. Therefore, If we modify or add any data in the copied dictionary, those modifications will not be reflected in the original dictionary.
Method signature
The signature for the copy() method is as shown below. Here, “c” is a shallow copy of the original dictionary, whereas “o” contains data that we are copying.
c=o.copy()
Method parameters and return type
- The copy() method doesn’t take any parameter.
- However, it returns the copy of the dictionary.
Python Dictionary Copy Examples:
Example 1:
Let us take a dictionary referred to as “e” that contains employee data in this example. Our first step will be to create a copy of our dictionary and we will call it “c”. As a result, it allocates separate memory location for “c” and copies the data from the dictionary “e” to the “c” dictionary.
#Initializing the Dictionary
e = {"Name":"Raj", "Salary":50000,"Experience":3.5}
# Creating copy of Dictionary
c=e.copy()
#Printing
print("Original Dictionary",e)
print("Copied Dictionary",c)
Output
Original Dictionary {'Name': 'Raj', 'Salary': 50000, 'Experience': 3.5}
Copied Dictionary {'Name': 'Raj', 'Salary': 50000, 'Experience': 3.5}
Example 2:
Let us take a dictionary referred to as “e” that contains employee data in this example. Our first step will be to create a copy of our dictionary and call it “c”. Thereafter, we will update the salary details in the shallow copy of the dictionary. So, it will not update the original content, but it will update the shallow copy data with new values.
#Initializing the Dictionary
e= {"Name":"Raj", "Salary":50000,"Experience":3.5}
# Creating copy of Dictionary
c=e.copy()
c["Salary"]=80000
#Printing
print("Original Dictionary",e)
print("Copied Dictionary",c)
Output
Original Dictionary {'Name': 'Raj', 'Salary': 50000, 'Experience': 3.5}
Copied Dictionary {'Name': 'Raj', 'Salary': 80000, 'Experience': 3.5}
Example 3:
In this example, To demonstrate the copy() method, let us use the “stud” dictionary of student marks. First, we will update the physics marks in the copied dictionary. Thereafter, we will update math marks in the original dictionary. As a result, We can see that the updates made to “stud” and “c” are independent of one another.
#Initializing the Dictionary
stud={"phy":50,"Chem":80,"Math":85}
# Creating copy of Dictionary
c=stud.copy()
c["phy"]=70
stud["Math"]=55
#Printing
print("Original Dictionary",stud)
print("Copied Dictionary",c)
Output
Original Dictionary {'phy': 50, 'Chem': 80, 'Math': 55}
Copied Dictionary {'phy': 70, 'Chem': 80, 'Math': 85}
Conclusion
The copy() method allocates the separate memory for copied dictionary. Hence, updates in the copied dictionary will not be reflected in the original dictionary.
References
Happy Learning 🙂