Python Dictionary copy()

They copy() method returns a shallow copy of the dictionary.

The syntax of copy() is:

dict.copy()

copy() Parameters

The copy() method doesn't take any parameters.


Return Value from copy()

This method returns a shallow copy of the dictionary. It doesn't modify the original dictionary.


Example 1: How copy works for dictionaries?

original = {1:'one', 2:'two'}
new = original.copy()

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

When you run the program, the output will be:

Orignal:  {1: 'one', 2: 'two'}
New:  {1: 'one', 2: 'two'}

Difference in Using copy() method, and = Operator to Copy Dictionaries

When copy() method is used, a new dictionary is created which is filled with a copy of the references from the original dictionary.

When = operator is used, a new reference to the original dictionary is created.


Example 2: Using = Operator to Copy Dictionaries

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

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

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

When you run the program, the output will be:

new:  {}
original:  {}

Here, when the new dictionary is cleared, the original dictionary is also cleared.


Example 3: Using copy() to Copy Dictionaries

original = {1:'one', 2:'two'}
new = original.copy()

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

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

When you run the program, the output will be:

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

Here, when the new dictionary is cleared, the original dictionary remains unchanged.