In this Python tutorial, you will learn what copy() method of dictionary dict class does, its syntax, and how to use this method to access copy the contents of a dictionary, with example programs.
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()
copy() method returns a new dictionary with the items of this dictionary.
Examples (2)
1. Make a copy of given dictionary
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)
Program Output
{'a': 58, 'b': 61, 'c': 39}
{'a': 58, 'b': 88, 'c': 39}
2. Understanding shallow copy of a dictionary
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)
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().