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.

Related Posts

  • Generate random number between 0 and 1 in Python
    15 July

    Generate random number between 0 and 1 in Python

    Table of ContentsUsing the random.uniform() function.Using the random.random() functionUsing the random.randint() functionUsing the numpy.random.random() functionUsing the numpy.random.uniform() function Generating Random numbers is easily achievable in Python, as Python provides the Random module that contains some functions that can be used to generate random numbers as per the programmer’s needs. A Random number does not generate […]

  • Convert String to Boolean in Python
    20 June

    Convert String to Boolean in Python

    Table of ContentsUsing the bool() method to convert string to Boolean in Python.Using the distutils.util.strtobool() method to convert a string to Boolean in Python.Using list comprehension to convert a string to Boolean in Python.Using the map() function along with Lambda function to convert a string to Boolean in Python.Using the JSON parser to convert a […]

  • Convert float to int in Python
    19 June

    Convert float to int in Python

    Table of ContentsUsing the int() function to convert float to int in PythonUsing the math module functions to convert float to int in PythonUsing ceil()Using trunc()Using floor Python provides several in-built functions and modules for datatype conversions. Floating-point numbers can be easily converted to integers using some of these in-built functions. This tutorial will discuss […]

  • Detect keypress in Python
    12 June

    Detect keypress in Python

    Table of ContentsUsing the keyboard module to detect keypress in PythonUsing the pynput module to detect keypress in PythonUsing the msvcrt module to detect keypress in Python Python allows us to work with user input in its programs. We can also work with hardware devices in Python. In this article, we will discuss how to […]

  • Escape quotes in Python
    11 June

    Escape quotes in Python

    Table of ContentsUsing \ to escape quotes in PythonUsing \ with replace() to escape quotes in PythonUsing json.dumps to escape quotes in PythonUsing triple single or double quotes to escape quotes in pythonUse r to include \ and quotes in String 💡 Outline You can use \ to escape quotes in Python. If you want […]

  • Sleep for milliseconds in python
    31 May

    How to sleep for milliseconds(ms) in Python

    Table of ContentsUse time.sleep() function to make the program sleep for millisecondsUse threading.Timer() function to make the program sleep for milliseconds 💡 Outline You can use time.sleep() method to sleep for milliseconds in Python. If you want to delay python program by 500 ms, then you need to pass 0.5 as parameter to sleep method. […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.