Python Dictionary copy() Method

Copies the dictionary shallowly

Usage

The copy() method returns the Shallow copy of the specified dictionary.

Syntax

dictionary.copy()

Example

D = {'name': 'Bob', 'age': 25}
X = D.copy()
print(X)
# Prints {'age': 25, 'name': 'Bob'}

copy() vs Assignment statement

Assignment statement does not copy objects. For example,

old_Dict = {'name': 'Bob', 'age': 25}
new_Dict = old_Dict
new_Dict['name'] = 'xx'
print(old_Dict)
# Prints {'age': 25, 'name': 'xx'}
print(new_Dict)
# Prints {'age': 25, 'name': 'xx'}

When you execute new_Dict = old_Dict, you don’t actually have two dictionaries. The assignment just makes the two variables point to the one dictionary in memory.

dict copy method vs assignment statement

So, when you change new_Dict, old_Dict is also modified. If you want to change one copy without changing the other, use copy()method.

old_Dict = {'name': 'Bob', 'age': 25}
new_Dict = old_Dict.copy()
new_Dict['name'] = 'xx'
print(old_Dict)
# Prints {'age': 25, 'name': 'Bob'}
print(new_Dict)
# Prints {'age': 25, 'name': 'xx'}

Equivalent Method

You can copy dictionary using dictionary comprehension as well.

D = {'name': 'Bob', 'age': 25}
X = {k:v for k,v in D.items()}
print(X)
# Prints {'age': 25, 'name': 'Bob'}