What is the purpose of the copy() method in Python dictionaries?

What is the purpose of the copy() method in Python dictionaries?

a) Creates a shallow copy of the dictionary
b) Creates a deep copy of the dictionary
c) Copies only the keys to a new dictionary
d) Copies only the values to a new dictionary

Answer:

a) Creates a shallow copy of the dictionary

Explanation:

The copy() method in Python dictionaries creates a shallow copy of the dictionary. This means that the new dictionary will have the same key-value pairs as the original, but changes to the new dictionary will not affect the original dictionary, and vice versa. However, if the values are mutable objects (like lists or dictionaries), changes to those objects will be reflected in both dictionaries.

# Example of copy() method
original = {"name": "John", "age": 20}
duplicate = original.copy()

# Modifying the copy
duplicate["age"] = 21
print(original)  # Output: {'name': 'John', 'age': 20}
print(duplicate)  # Output: {'name': 'John', 'age': 21}

In this example, the copy() method creates a shallow copy of the original dictionary. Changes made to the duplicate dictionary do not affect the original dictionary.

The copy() method is useful when you need a new dictionary that is a duplicate of the original but independent of it, allowing you to make changes without altering the original data.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top