Python Dictionary copy() Method

The copy() method creates a shallow copy of a dictionary.

A shallow copy means that a new dictionary is created, but its values reference the original. If the values are mutable like a list or nested dictionary, changes to them in the copy will also affect the original.

Syntax

new_dict = original_dict.copy()

Parameters

It doesn’t accept any arguments.

Return Value

It returns a shallow copy of a dictionary. It doesn’t modify the original dictionary.

Example:

original_dict = {"name": "James", "age": 35, "city": "London"}

copied_dict = original_dict.copy()
print(copied_dict) # Output: {'name': 'James', 'age': 35, 'city': 'London'}

Example of shallow copy behavior

original_dict = {'a': 1, 'b': [2, 3]}

# Creating a shallow copy
copied_dict = original_dict.copy()

# Modifying the copied dictionary
copied_dict['a'] = 5
copied_dict['b'].append(4)

print("Original Dictionary:", original_dict)
print("Copied Dictionary:", copied_dict)

Output:

Original Dictionary: {'a': 1, 'b': [2, 3, 4]}
Copied Dictionary: {'a': 5, 'b': [2, 3, 4]}

Explanation:

Modifying the key a in the copied dictionary won’t affect the original dictionary because integers are immutable. However, modifying the key b in the copied dictionary also changes the original because lists are mutable and both dictionaries reference the same object.

Deep Copy

If you need a completely independent copy of the dictionary (including all nested objects), you can use the copy.deepcopy() method of the copy module.

For example:

import copy
original_dict = {'a': 1, 'b': [2, 3]}

# Creating a deep copy
deep_copied_dict = copy.deepcopy(original_dict)

# Modifying the deep copied dictionary
deep_copied_dict['a'] = 5
deep_copied_dict['b'].append(4)

print("Original Dictionary:", original_dict)
print("Deep Copied Dictionary:", deep_copied_dict)

Output:

Original Dictionary: {'a': 1, 'b': [2, 3]}
Deep Copied Dictionary: {'a': 5, 'b': [2, 3, 4]}

The original dictionary remains unchanged even when the deep copied dictionary is modified.