7 ways to copy a dictionary in python

Copy a dictionary in Python

💡 Outline
**Shallow copy**
You can use copy method of Dictionary to create shallow copy of dictionary in Python.

**Deep copy**
You can use deepcopy() function of copy module to create deep copy of dictionary in Python.

Dictionaries are a mutable structure in Python. We can alter the key-value pairs in a dictionary without changing its identity, which can be considered as the object’s memory location. We can create clones of a dictionary in Python.

Note that we cannot use the assignment operator to create such copies. The code dictionary_1 = dictionary_2 will not result in a copy but just give another name to reference the same object.

In this tutorial, we will learn how to copy a dictionary in Python.

Using the copy() function to copy a dictionary in Python

The copy() function from the copy module is used to create shallow copies of an object. A shallow copy takes the parent object and fills it with references to the elements in the original object. Any changes made in a shallow copy will also reflect in the original object.

We can use it to copy a dictionary as shown below.

Output:

{‘a’: 1, ‘b’: 2, ‘c’: 3}

Alternatively, we can also use the copy() function from the dictionary class. It provides the exact same result.

Output:

{‘a’: 1, ‘b’: 2, ‘c’: 3}

Using the deepcopy() function to copy a dictionary in Python

A deep copy constructs a new object and then recursively constructs the elements of this object. A change made in a deep copy will not affect the original object.

We can use the deepcopy() function from the copy module to create such copies.

For example,

Output:

{‘a’: 1, ‘b’: 2, ‘c’: 3}

Using the dict() function to copy a dictionary in Python

The dict() function is used to initialize dictionaries in Python. We can use it to create a shallow copy of a dictionary.

See the code below.

Output:

{‘a’: 1, ‘b’: 2, ‘c’: 3}

Using the unpack operator ** to copy a dictionary in Python

The unpacking operator is an addition to recent versions of Python. It can be used as * and **. For dictionaries, we use the **. It is used to unpack or extract all the components from an iterable object. It can be used to create a copy of a dictionary.

For example,

Output:

{‘a’: 1, ‘b’: 2, ‘c’: 3}

Note that this also creates a shallow copy. It works only in Python 3.5 and above.

Using the update() function to copy a dictionary in Python

The update() function is used to add or alter the key-value pairs of a dictionary.

We can use it in the following way to create a shallow copy of a dictionary.

Output:

{‘a’: 1, ‘b’: 2, ‘c’: 3}

Using the dictionary comprehension method to copy a dictionary in Python

A dictionary comprehension method can be used to create dictionaries in single lines of code. It is a very compact and elegant method and usually requires the use of loops.

We can create shallow copies of a dictionary using this as shown below.

Output:

{‘a’: 1, ‘b’: 2, ‘c’: 3}

The items() function returns an object containing key-value pairs of a dictionary in as tuples in a list.

For Python v2.7 and above, we can do it in the following way also.

Output:

{‘a’: 1, ‘b’: 2, ‘c’: 3}

Using the for loop to copy a dictionary in Python

Dictionary can be iterated over in Python using the for loop. We can access keys and values individually and assign them to a new dictionary. It creates a deep copy.

For example,

Output:

{‘a’: 1, ‘b’: 2, ‘c’: 3}

This however only works with simple dictionaries. The deepcopy() function from the copy module does the same process internally.

Conclusion

In this article, we discussed many methods to create a copy of a dictionary. However, most of these methods return a shallow copy of a dictionary. If one wants an actual copy, then he or she must want the copy to not affect the original dictionary, something which does not happen with shallow copies. So for most purposes, kindly use the deepcopy() function which will create a deep copy of the required dictionary.

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • 29 June

    Get Day Name from Date in Python

    Table of ContentsUse the Calendar Module to Get the Name of the Day in PythonUse the strftime() Method to Get the Name of the Day in PythonUse Pandas Timestamp Method to Get the Name of the Day in PythonUse the weekday() Method to Get the Name of the Day in PythonUse the isoweekday() Method to […]

  • 27 June

    Fill Array with Random Numbers in Python

    Table of ContentsFill array with random numbers in PythonWays to fill array with random numbers in PythonUsing the numpy.random.randint() function to fill array with random numbers in PythonUsing the numpy.random.Generator.integers() function to fill array with random numbers in PythonUsing the random.randint() function to fill array with random numbers in PythonConclusionWas this post helpful? Fill array […]

  • 25 June

    Convert Roman Number to Integer in Python

    Table of ContentsHow to Convert Roman Number to Integer in PythonHow to convert roman number to integer in python?Using the if...else statement to convert roman number to integer in Python.Using classes and a dictionary to convert roman number to integer in Python.Using the roman module to convert roman number to integer in Python.ConclusionWas this post […]

  • 11 June

    Remove Single Quotes from String in Python

    Table of ContentsRemove single quotes from string in Python.How to remove single quotes from string in Python?Using the replace() function to remove single quotes from string in Python.Using a for loop to remove single quotes from string in Python.Using the join() function to remove single quotes from string in Python.Using the re module functions to […]

  • 11 June

    Escape Backslash Character in Python

    Table of ContentsEscape backslash character in python.How to use escape backslash character in python?Using the escape backslash character in python to represent whitespace characters.Using the escape backslash character in python to turn special characters into ordinary characters.Using the escape backslash character in f-strings in Python.Using the escape backslash character in raw strings in Python.Was this […]

  • 11 June

    Break out of function in Python

    Table of ContentsBreak out of function in PythonHow to break out of function in Python?Using the return statement to break out of function in PythonUsing the try and except block to break out of function in PythonUsing the sys.exit() function to break out of function in PythonConclusionWas this post helpful? In this post, we will […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.