How can I Python copy dictionary to avoid modifying the original when editing the copy?

How can I Python copy dictionary to avoid modifying the original when editing the copy?

For example, I have the following dictionary:

dict1 = {"key1": "value1", "key2": "value2"}
dict2 = dict1
dict2["key2"] = "WHY?!"

When I edit dict2, the original dict1 also changes. How can I create a copy of dict1 and only modify the copy, leaving the original intact?

The simplest way to create a shallow copy of a dictionary in Python is to use the copy() method. This ensures that the original dictionary remains unchanged.

dict1 = {"key1": "value1", "key2": "value2"}
dict2 = dict1.copy()
dict2["key2"] = "WHY?!"
print(dict1)  # Output: {'key1': 'value1', 'key2': 'value2'}
print(dict2)  # Output: {'key1': 'value1', 'key2': 'WHY?!'}

Using copy module for deep copy: If the dictionary contains nested objects (e.g., lists or other dictionaries), you should use deepcopy() from the copy module to avoid modifying the nested structures in the original dictionary.

import copy
dict1 = {"key1": "value1", "key2": {"nestedKey": "nestedValue"}}
dict2 = copy.deepcopy(dict1)
dict2["key2"]["nestedKey"] = "modifiedValue"
print(dict1)  # Output: {'key1': 'value1', 'key2': {'nestedKey': 'nestedValue'}}
print(dict2)  # Output: {'key1': 'value1', 'key2': {'nestedKey': 'modifiedValue'}}

Using the dict() constructor: You can also create a copy of a dictionary using the dict() constructor, which works similarly to the copy() method.

dict1 = {"key1": "value1", "key2": "value2"}
dict2 = dict(dict1)
dict2["key2"] = "WHY?!"
print(dict1)  # Output: {'key1': 'value1', 'key2': 'value2'}
print(dict2)  # Output: {'key1': 'value1', 'key2': 'WHY?!'}