In this article we will discuss how to create a shallow and deep copy of dictionary in Python.

Create Shallow copy of Dictionary using dict.copy()

Python’s dictionary provides a member function copy() i.e.

It returns a shallow copy of the existing dictionary.

What is a shallow copy ?

Shallow copy means a new dictionary object will be created and reference to the objects in existing dictionary will be inserted in this.

Let’s understand by some examples,

Suppose we have a dictionary of with key string and value as int or list of int i.e.

Now create a Copy of this dictionary using dict.copy() i.e.

Now this new dictionary will contain shallow copy of all the elements from original dictionary.

Contents of New Dictionary is :

Let’s modify the new dictionary by changing the value of a key ‘at’ i.e.

Now Contents of new Dictionary is,

Now check the contents of original dictionary i.e.

Value of key ‘at’ is different in both. So, modifying the new dictionary didn’t changed the original dictionary contents. Then how it is shallow ?

The word Shallow copy comes in picture when there is some object in dictionary like list or user define objects instead of primitive datatypes.

Now let’s modify the value of key that contains list as value i.e.

Now Contents of new Dictionary is,

Now check the contents of original dictionary i.e.

We changed the contents of shallow copied dictionary but changes are now reflected in original dictionary too. It happened because reference to list object in original dictionary was copied in new dictionary. So, any changes in that list will be reflected in both the dictionaries.

To avoid this kind of thing we can use deepcopy() to create a deep copy of the dictionary.

Create a deep copy of dictionary using copy.deepcopy()

In Python copy module provides a function deepcopy() i.e.

It accepts a dictionary as parameter and returns a new dictionary with copy all the objects recursively.

Suppose we have a dictionary i.e.

Let’s create a deep copy of this dictionary,

Now any modification in this copy will not be reflected in original copy i.e.

Contents of Deep Copy Dictionary:

Contents of Original Dictionary:

Contents of both the dictionaries are different and modification in one will not affect other copy because its a deep copy.

Complete example is as follows :



Click Here to Subscribe for more Articles / Tutorials like this.