Python Dictionary copy() Method

Copies the dictionary shallowly

Usage

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

Syntax

dictionary.copy()

Example

Example: Copy entire dictionary

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

copy() vs Assignment statement

Assignment statement does not copy objects. For example,

Example:

old_Dict = {'name': 'Bob', 'age': 25}
new_Dict = old_Dict
new_Dict['name'] = 'xx'
print(old_Dict)     # {'age': 25, 'name': 'xx'}
print(new_Dict)     # {'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.

Example:

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

Equivalent Method

You can copy dictionary using dictionary comprehension as well.

Example: Copy entire dictionary with dictionary comprehension

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