Python Dictionary copy()

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

Example


Syntax of Dictionary copy()

The syntax of copy() is:

dict.copy()

copy() Arguments

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


copy() Return Value

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


Example 1: How copy works for dictionaries?

Output

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

Dictionary copy() Method Vs = Operator

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

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


Example 2: Using = Operator to Copy Dictionaries

Output

new:  {}
original:  {}

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


Example 3: Using copy() to Copy Dictionaries

Output

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

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