Python dict.copy() Method

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.

Definition: 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 of Python’s dict.copy() Method

Method Declaration dict.copy():

dict.copy()

Method Parameters dict.copy():

Python’s dict.copy() method does not input any parameters.

Method Return Value dict.copy():

The dict.copy() method outputs 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.

Basic Example using dict.copy() Method

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.

Output:

original dictionary:  {'ebook': 'python-book', 'video': 'freelance-video', 'computer': 'laptop'}
new dictionary:  {'ebook': 'python-book', 'video': 'freelance-video', 'computer': 'laptop'}

Dictionary dict.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.

Example using the = Operator:

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:  {}