π Summary: There are many different ways to copy the dictionary data structure objects in Python. In this tutorial, I will show you the built-in dict.copy()
method, which is a very useful method for copying dictionaries.
Description
Whenever the dict.copy()
method is applied to a dictionary, a new dictionary is made, which contains a copy of references from the original dictionary.
Syntax
dict.copy()
Python’s dict.copy()
method does not input any parameters.
The return value of the dict.copy()
method is a shallow copy of a dictionary. That is, it copies the dictionary structure, but the cloned dictionary structure still refers to the elements of the original object.
If you want a deep copy, you can check out our other overview article here:
π Recommended Tutorial: 7 Pythonic Ways to Copy a Dictionary
Example
The following example creates a dictionary original_dict
with three key-value pairs, copies it, and assigns the copied dictionary to the variable new_dict
:
original_dict = {'ebook': 'python-book', 'video': 'freelance-video', 'computer': 'laptop'} new_dict = original_dict.copy() print('original dictionary: ', original_dict) print('new dictionary: ', new_dict) # Note: the 2 outputs will be the same.
Both dictionaries look the same:
original dictionary: {'ebook': 'python-book', 'video': 'freelance-video', 'computer': 'laptop'} new dictionary: {'ebook': 'python-book', 'video': 'freelance-video', 'computer': 'laptop'}
However, they actually do refer to different objects in memory. If you change the original dictionary, the change is not reflected in the new dictionary:
original_dict['ebook'] = 'xxx' print(original_dict['ebook']) # xxx print(new_dict['ebook']) # python-book
You can see this yourself in the following memory visualizer—click the forward and backward buttons to go through the code. And consider that you have two dicts in memory after termination!
Dictionary copy() vs Assignment = Operator
When the dict.copy()
method is applied to a dictionary, a new dictionary is made, which contains the references from the original dictionary.
When the equal = operator is applied, a new reference to the original dictionary is made.
Here’s an example:
grocery_dict = {'juice': 'apple', 'drink': 'tea', 'fruit': 'melon'} new_grocery = grocery_dict new_grocery.clear() print('original grocery dict: ', grocery_dict) print('original grocery dict: ', grocery_dict) # Note: outputs are both an empty dictionary: {}
Output:
original grocery dict: {} original grocery dict: {}
You can see that the assignment operator just makes it so that both variables point to the same object in memory:
π Recommended Tutorial: Python is vs equal Operator