Skip to content

Python copy dictionary | copy() function

  • by

Use copy() method to copy the dictionary in Python. This method returns a copy (shallow copy) of the dictionary and doesn’t take any parameters.

dict.copy()

Example how to copy a dictionary in Python

Simple example code.

original = {1: 'A', 2: 'B'}

copy_dict = original.copy()
print(copy_dict)

Output:

Python copy dictionary

If you need a deep copy (a copy that does not share references to the original object), you can use the copy module:

import copy

original_dict = {'key1': [1, 2], 'key2': 'value2'}
new_dict = copy.deepcopy(original_dict)

How is it different from simple assignment “=”?

Answer: Copying the dictionary using the copy() method creates a copy of the references from the original dictionary.

Where the = operator creates a new reference to the original dictionary is created.

original = {1:'one', 2:'two'}
new = original


# removing all elements from the list
new.clear()

print('new: ', new)
print('original: ', original)

Output:

new: {}
original: {}

Comment if you have any doubts or suggestions on this Python copy() function code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading