Python Dictionary copy() Method With Examples

Python Dictionary copy

Now, we are going to learn about the copy method, using which, we can make a copy of the dictionary.

Well, in some situations, you might want to get a copy of your dictionary. In such situations, the copy method is our escape. But if you are wondering what is the need for some method for doing so? We can just create a new reference variable, and then assign the existing reference variable to it, and we will have a copy of the dictionary. But this is not as we are thinking. Let’s try doing this.

Python Dictionary copy() Method

As you can see in the above program, we have a simple dictionary, and then we are simply doing copy_dict = sample_dict, which means that we are simply using the assignment operator. If we are doing so, we are not creating a copy of the dictionary. Instead, we are just creating another reference variable, which points to the same dictionary. So, there are two reference variables, pointing to an object. But someone can mistakenly think that we have made a copy of the dictionary.

Due to this assignment, the copy_dict is now referring to the same dictionary, as the sample_dict. So, any changes that we would do to the copy_dict, would be on the sample_dict. So, as you can see, we added the element with key ‘four’, and it got added for the sample_dict, which was not supposed to happen.

So, in order to have a copy of this dictionary, we need to make use of the copy method. Have a look at the below program, where we are using the copy method to create a copy of the dictionary.

As you can see in the above program, we are using the copy method to get a copy of the dictionary. Now, since we are having two different dictionaries, the changes made to one dictionary, won’t affect the other dictionary.  As you can see, now we have got a copy of that dictionary. Again, we are adding a new element with key ‘four’ in the copied dictionary, and it is only getting added to the copied dictionary, and not the original dictionary. We have also printed both dictionaries to cross-check things. Have a look at the output now –

C:\Users\GyaniPandit\Desktop\python> python dictionary.py
{‘one’: 1, ‘two’: 2, ‘three’: 3}
{‘one’: 1, ‘two’: 2, ‘three’: 3, ‘four’: 4}

So, now we understand that using the copy method, we can simply get a copy of the dictionary in our program. So, whenever we need to have a copy of our dictionary, we can simply make use of the copy method.