In my previous articles we discussed the following dictionary methods:
– get
– fromkeys
Feel free to read about them if you haven’t done so yet.
In this article we’ll be talking about the dictionary method copy.
Here’s the video version of this article:
We use the copy method to copy a dictionary:
>>> rooms = {"Steven" : 42, "Natalie" : 12, "Peter" : 112, "Francis" : 14}
>>> rooms_copy = rooms.copy()
>>> print(rooms)
{'Steven': 42, 'Natalie': 12, 'Peter': 112, 'Francis': 14}
>>> print(rooms_copy)
{'Steven': 42, 'Natalie': 12, 'Peter': 112, 'Francis': 14}
>>> rooms_copy["Peter"] = 115
The change is now visible in the copy where it was made, but not in the original:
>>> rooms
{'Steven': 42, 'Natalie': 12, 'Peter': 112, 'Francis': 14}
>>> rooms_copy
{'Steven': 42, 'Natalie': 12, 'Peter': 115, 'Francis': 14}
What we get using the copy method is a shallow copy. If you want to learn more about the difference between shallow copies and deep copies, you can read these two articles:
– Copying Lists – Shallow Copies
They are about lists, and, as you know, lists can be used as values in a dictionary.
So, if a value in the dictionary is a complex data type (like a list), only the reference will be copied:
>>> results = {"Anne" : 5, "George" : [4,6]}
>>> results_copy = results.copy()
Just checking if the copy method worked. It did:
>>> results
{'Anne': 5, 'George': [4, 6]}
>>> results_copy
{'Anne': 5, 'George': [4, 6]}
Let’s change the second element in the list in the copy:
>>> results_copy["George"][1] = 7
The change is now visible in both the original and the copy:
>>> results
{'Anne': 5, 'George': [4, 7]}
>>> results_copy
{'Anne': 5, 'George': [4, 7]}
Now let’s change the whole list:
>>> results_copy["George"] = [3,8]
This time the change is visible only in the copy.
>>> results
{'Anne': 5, 'George': [4, 7]}
>>> results_copy
{'Anne': 5, 'George': [3, 8]}