Python copy dictionary | copy() function

Use copy() method to copy 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 dictionary in Python

Simple example code.

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

copy_dict = original.copy()
print(copy_dict)

Output:

Python copy dictionary

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

Do comment if you have any doubts and suggestions on this Python copy() function code.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.