/  Technology   /  How to copy a dictionary and only edit the copy

How to copy a dictionary and only edit the copy

How to copy a dictionary and only edit the copy

 

We can copy the data from one dictionary to another using some of these ways:

  • deepcopy()
  • copy()
  • dict()
  • “=” operator

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 way in detail.

  1. Using deepcopy()

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

>>> import copy

>>> d1 = {‘a’:1}

>>> d2 = copy.deepcopy(d1)

>>> d2

{‘a’: 1}

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

>>> d2[‘a’] = 7

>>> d2

{‘a’: 7}

>>> d1

{‘a’: 1}

 

  1. Using copy()

Another solution for this is using the copy() function

>>> d2 = d1.copy()

But this function is also a 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.

d1 = {‘a’:1}

However, if the values associated with the dictionary keys are iterable objects, then if one dictionary’s data is modified then the other one will also get modified.

>>> d1 = {‘a’:[1,2,3]}

Note: An iterable is any Python object capable of returning its members one at a time,i.e. each element is responsible for returning the next element in lists, tuples, and strings – any such sequence can be iterated over in a for-loop.

 

  1. Using the “=” operator 

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

  1. Using dict()

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

>>> d2 = dict(d1)

Now going back to the question, if we want to copy a dictionary and want to edit or modify the second dictionary we can only do it using the deepcopy() irrespective of the type of data, and we can use copy(), dict() only when non-iterable objects are associated with the dictionary.

Rest all the ways i.e. using “=” operator , using copy() and dict() when we have iterable objects associated with the dictionary, cannot be used to specifically edit the second dictionary.

 

 

Leave a comment