How to Copy a Dictionary in Python

Spread the love

Copy Method –

The copy method returns a shallow copy of a dictionary. This does not modify the original dictionary.

Syntax of copy –


Let’s say we have a dictionary which contains some information about a person.

In [1]: person1 = {'Name':'Emma', 'Age': 25, 'Location': 'California'}

Now, we want to copy this information into another dictionary. For this we can use the dictionary copy method.

In [2]: person2 = person1.copy() 

In [3]: person2
Out[3]: {'Name': 'Emma', 'Age': 25, 'Location': 'California'}

Difference between Copy method vs = operator

You can also copy a dictionary using the equal operator but there is a big difference between the two.

Let’s first look at copying a dictionary using the equal operator.

In [4]: person1 = {'Name':'Emma', 'Age': 25, 'Location': 'California'}

In [5]: person2 = person1

In [6]: person2
Out[6]: {'Name': 'Emma', 'Age': 25, 'Location': 'California'}

Here, we copied a dictionary using the equal operator. Now if I change the copied dictionary the original dictionary will be also changed.

In [7]: person2.clear()

In [8]: person2
Out[8]: {}

In [9]: person1
Out[9]: {}

Here, I removed all the key-value pairs from the copied dictionary which also cleared all the key-value pairs of the original dictionary which you may not want.

But if you copy a dictionary using the copy() method and then change the copied dictionary, it won’t effect the original dictionary.

In [10]: person1 = {'Name':'Emma', 'Age': 25, 'Location': 'California'}

In [11]: person2 = person1.copy()

In [12]: person2.clear()

In [13]: person2
Out[13]: {}

In [14]: person1
Out[14]: {'Name': 'Emma', 'Age': 25, 'Location': 'California'}

Rating: 1 out of 5.

Leave a Reply