5 Ways to Make a Shallow Copy of a Dictionary Explained

5 Ways to Make a Shallow Copy of a Dictionary Explained

You can create a shallow copy of a dictionary using the copy() method or the dict() constructor. Here are five examples demonstrating how to create shallow copies of dictionaries:

  1. Using the copy() method:
original_dict = {'a': 1, 'b': 2, 'c': 3}
shallow_copy = original_dict.copy()

# Modify the original dictionary
original_dict['a'] = 100

print(original_dict)  # Output: {'a': 100, 'b': 2, 'c': 3}
print(shallow_copy)   # Output: {'a': 1, 'b': 2, 'c': 3}
  1. Using the dict() constructor:
original_dict = {'a': 1, 'b': 2, 'c': 3}
shallow_copy = dict(original_dict)

# Modify the original dictionary
original_dict['a'] = 100

print(original_dict)  # Output: {'a': 100, 'b': 2, 'c': 3}
print(shallow_copy)   # Output: {'a': 1, 'b': 2, 'c': 3}
  1. Creating a shallow copy of an empty dictionary:
original_dict = {}
shallow_copy = original_dict.copy()

# Add a key-value pair to the original dictionary
original_dict['a'] = 1

print(original_dict)  # Output: {'a': 1}
print(shallow_copy)   # Output: {}
  1. Creating a shallow copy of a dictionary with mutable values:
original_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
shallow_copy = original_dict.copy()

# Modify the value in the original dictionary
original_dict['a'][0] = 100

print(original_dict)  # Output: {'a': [100, 2, 3], 'b': [4, 5, 6]}
print(shallow_copy)   # Output: {'a': [100, 2, 3], 'b': [4, 5, 6]}
  1. Creating a shallow copy of a dictionary containing dictionaries:
original_dict = {'a': {'x': 1, 'y': 2}, 'b': {'z': 3}}
shallow_copy = original_dict.copy()

# Modify the value in the original dictionary
original_dict['a']['x'] = 100

print(original_dict)  # Output: {'a': {'x': 100, 'y': 2}, 'b': {'z': 3}}
print(shallow_copy)   # Output: {'a': {'x': 100, 'y': 2}, 'b': {'z': 3}}

In all examples, modifications made to the original dictionary do not affect the shallow copy, demonstrating that a shallow copy creates a new dictionary object with references to the same key-value pairs as the original dictionary. However, changes to mutable values within the dictionary will affect both the original and shallow copy if they reference the same objects.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!