/  Technology   /  How to copy a dictionary and only edit the copy in Python?
How to copy a dictionary and only edit the copy in python

How to copy a dictionary and only edit the copy in Python?

 

We have considered a dictionary named d1 with the following elements and we assign this to a new dictionary named d2 using the “=” operator. 

 

Example:

d1 = {'a':1}
d2=d1
print(d2)

Output:

 

Now after altering the data in d1, if we try to print d2, the change is reflected in it too.

 

Example:

d1 = {'a':1}
d2=d1
print(d2)
d2['a']=2
print("Second Dictionary is:"+str(d2))
print("First Dictionary is:"+str(d1))

Output:

 

Why is this happening?

It’s because, when we use the “=” operator, we are not really making a copy, it is more like a dictionary with two names, if one dictionary is modified the other gets modified too.

 

What do we do if we want the copied dictionary to be unaltered?

There are several ways to do this task. Let’s discuss a few in this article,

  • deepcopy()
  • copy()
  • dict()

 

Before we jump into studying each one of these let’s understand these two terms first:

 Deep Copy : 

It stores copies of the object’s value. This doesn’t reflect changes made to the new/copied object in the original object.

 Shallow Copy:

It stores the references of objects to the original memory address. This reflects changes made to the new/copied object in the original object.

 

Let’s now study each method in detail.

 

1. Using deepcopy()

Using this, we can get a copy of a dictionary completely independent of the first dictionary. 

d2 = copy.deepcopy(d1)

 

Example:

import copy
d1 = {'a':1}
d2 = copy.deepcopy(d1)
print("Second Dictionary before altering is:"+ str(d2))

d2['a'] = 7
print("Second Dictionary after altering is:"+str(d2))
print("First Dictionary after altering is:"+str(d1))

Output:

Now if we try to modify the second dictionary, the first dictionary’s data isn’t changing.

 

2. Using copy()

Another solution for this is using the copy() function

d2 = d1.copy()

This function also performs shallow copy and if the values associated with the dictionary keys are not iterable objects, then if one of the dictionaries is modified the other one will not be.

 

Example:

import copy
d1 = {'a':1}
d2 = d1.copy()
print("Second Dictionary before altering is:"+ str(d2))

d2['a'] = 7
print("Second Dictionary after altering is:"+str(d2))
print("First Dictionary after altering is:"+str(d1))

Output:

 

3. Using dict()

Its function is much similar to copy(). It also makes a shallow copy of the first dictionary.

 

Example:

d1 = {'a':1}
d2 = dict(d1)
print("Second Dictionary before altering is:"+ str(d2))

d2['a']=2
print("Second Dictionary after altering is:"+str(d2))
print("First Dictionary after altering is:"+str(d1))

Output:

 

Leave a comment