Dictionary copy() Method in Python

Python Dictionary copy() Method

The copy() method in Python dictionaries is used to create a shallow copy of a dictionary. It returns a new dictionary with the same key-value pairs as the original dictionary. However, it does not create copies of the objects that are the values of the dictionary. Instead, it copies references to the same objects in the new dictionary. This means that changes made to mutable objects within the dictionary will be reflected in both the original and copied dictionaries.

Here's the syntax of the copy() method:

new_dict = old_dict.copy()

Now, let's see some examples:

Example 1: Copying a dictionary with immutable values

# Original dictionary
original_dict = {'a': 1, 'b': 2, 'c': 3}

# Create a shallow copy of the dictionary
copied_dict = original_dict.copy()

# Modify the copied dictionary
copied_dict['b'] = 99

# Print both dictionaries
print("Original Dictionary:", original_dict)
print("Copied Dictionary:", copied_dict)

Output:

Original Dictionary: {'a': 1, 'b': 2, 'c': 3}
Copied Dictionary: {'a': 1, 'b': 99, 'c': 3}

As you can see, modifying the value of 'b' in the copied dictionary does not affect the original dictionary since integers are immutable.

Example 2: Copying a dictionary with mutable values

# Original dictionary with lists as values
original_dict = {'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]}

# Create a shallow copy of the dictionary
copied_dict = original_dict.copy()

# Modify the copied dictionary (append a value to the list)
copied_dict['b'].append(99)

# Print both dictionaries
print("Original Dictionary:", original_dict)
print("Copied Dictionary:", copied_dict)

Output:

Original Dictionary: {'a': [1, 2, 3], 'b': [4, 5, 6, 99], 'c': [7, 8, 9]}
Copied Dictionary: {'a': [1, 2, 3], 'b': [4, 5, 6, 99], 'c': [7, 8, 9]}

In this case, since the values in the dictionary are lists (mutable), modifying the list in the copied dictionary also affects the original dictionary.

Remember, the copy() method creates a shallow copy. If you have nested dictionaries or complex data structures within your dictionary, you might need to use the copy module's deepcopy() method to create a fully independent copy.