Python Dictionary copy()

Python Dictionary copy() method returns a shallow copy of the dictionary. We shall learn in detail what this shallow copy is, with the help of examples.

In this tutorial, we will learn the syntax of copy() method and its usage using example programs.

Syntax

The syntax of dict.copy() is

dict.copy()
Try Online

copy() method returns a new dictionary with the items of this dictionary.

Example 1 – Python dict.copy()

This is a simple example, where we shall copy a dictionary. We will make some updates to the copy version of dictionary and find the changes happened to the original and copy version of dictionaries.

Python Program

dictionary1 = {'a': 58, 'b': 61, 'c': 39}
dictionary2 = dictionary1.copy()
dictionary2['b'] = 88
print(dictionary1)
print(dictionary2)
Try Online

Program Output

{'a': 58, 'b': 61, 'c': 39}
{'a': 58, 'b': 88, 'c': 39}

Example 2 – Python dict.copy() – Understanding Shallow Copy

We already mentioned that copy() method only does a shallow copy of the dictionary. If dictionary contains any other objects as values, say a list of items, user defined object, tuple, another dictionary, etc., copies of these objects will not be made but the references are copied. So, if you make any updates to these referenced values, original dictionary also gets updated.

In the following program, we shall demonstrate this scenario using a list as value for the key 'b'.

Python Program

list1 = [41, 58]
dictionary1 = {'a': 58, 'b': list1, 'c': 39}
dictionary2 = dictionary1.copy()
dictionary2['b'][0] = 99
print(dictionary1)
print(dictionary2)
Try Online

Program Output

{'a': 58, 'b': [99, 58], 'c': 39}
{'a': 58, 'b': [99, 58], 'c': 39}

'b': [41, 58] is updated to 'b': [99, 58] in both the original and copy versions of dictionary.

Conclusion

In this Python Tutorial, we learned about Python Dictionary method dict.copy(). We have gone through the syntax of copy(), and its usage with example programs.