search

How to create a shallow copy of a dictionary in Python?

In Python, you can create a shallow copy of a dictionary using the copy() method or the dict() constructor. Both methods create a new dictionary object that shares the references to the original dictionary's keys and values. Here are the ways to create a shallow copy:

Using the copy() method:

original_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# Create a shallow copy using the copy() method
shallow_copy = original_dict.copy()

Using the dict() constructor:

original_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# Create a shallow copy using the dict() constructor
shallow_copy = dict(original_dict)

After creating a shallow copy, any modifications made to the keys or values in the original dictionary will also be reflected in the shallow copy, as they share the same references.

Here's an example to demonstrate this behavior:

original_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

shallow_copy = original_dict.copy()

# Modify the original dictionary
original_dict['age'] = 31

print(original_dict)    # Output: {'name': 'John', 'age': 31, 'city': 'New York'}
print(shallow_copy)     # Output: {'name': 'John', 'age': 30, 'city': 'New York'}

In this example, modifying the 'age' key in the original dictionary does not affect the shallow copy, as it maintains its original value.

Creating a shallow copy can be useful when you need a separate dictionary object that shares the underlying data with the original dictionary. However, if you want to create a completely independent copy of the dictionary, including nested objects, you should use a deep copy instead.

Related Questions You Might Be Interested