How to Copy a dictionary in Python
In this tutorial, we are going to understand how to copy a dictionary in Python. We can copy all the contents of one dictionary to another dictionary with the help of copy() method or assignment operator. The difference between copying using assignment operator and using copy() is that when we copy a dictionary using assignment operator, any operation done on the new dictionary which contains the copied elements will also make changes in the original dictionary.
On the other hand, if we copy the contents of a dictionary using copy() method any changes made to the dictionary containing copied elements will not affect the original dictionary.
Python program to copy dictionary
Contents of the dictionary:
marks={‘Operating System’:74,’Java’:72,’Python’:88,’c++’:82}
Copying the contents of the dictionary using an assignment operator
marks={'Operating System':74,'Java':72,'Python':88,'c++':82} copy_marks=marks copy_marks
Copying the content of marks to copy_marks.
Output
{‘Operating System’: 74, ‘Java’: 72, ‘Python’: 88, ‘c++’: 82}
marks={'Operating System':74,'Java':72,'Python':88,'c++':82} copy_marks_new=marks.copy() copy_marks_new
Copying the content of marks to copy_marks_new.
Output
{'Operating System': 74, 'Java': 72, 'Python': 88, 'c++': 82}.
The difference between copying using the assignment operator and copy method.
Assignment operator
marks={'Operating System':74,'Java':72,'Python':88,'c++':82} copy_marks=marks copy_marks.clear() copy_marks marks
Here we can see that we are removing the elements of dictionary copy_marks using clear() function, as we are clearing the elements from copy_marks we can see that the elements of the original dictionary marks are also been deleted.
Output
{} {}
Copy method
marks={'Operating System':74,'Java':72,'Python':88,'c++':82} copy_marks_new=marks.copy() copy_marks_new.clear() copy_marks_new marks
Here we can see that we are removing the elements of dictionary copy_marks_new using clear() function, as we are clearing the elements from copy_marks_new we can see that the elements of the original dictionary marks remain unaffected.
Output
{}
{'Operating System': 74, 'Java': 72, 'Python': 88, 'c++': 82}
Leave a Reply