create independant copy of a dictionnary in python

To create an independent copy of a dictionary in Python, you need to use the "copy" module. However, be careful when copying a dictionary as it is a mutable object. If you create a shallow copy, changing one copy of the dictionary could modify the original dictionary. To avoid this issue, you can use the "deepcopy" method from the "copy" module.

Here is an example to create a shallow copy of a dictionary:

main.py
original_dict = {"key1": "value1", "key2": "value2"}
new_dict = original_dict.copy()

# Modify the new_dict
new_dict["key1"] = "new_value1"

# Verify that the original dictionary has not been modified
print(original_dict)  # Output: {'key1': 'value1', 'key2': 'value2'}

271 chars
10 lines

And here is an example to create a deep copy of a dictionary:

main.py
import copy

original_dict = {"key1": {"inner_key1": "value1"}, "key2": "value2"}
new_dict = copy.deepcopy(original_dict)

# Modify the new_dict
new_dict["key1"]["inner_key1"] = "new_value1"

# Verify that the original dictionary has not been modified
print(original_dict)  # Output: {'key1': {'inner_key1': 'value1'}, 'key2': 'value2'}

338 chars
12 lines

In the second example, we use the "deepcopy" method from the "copy" module to create an independent copy of the original dictionary. We then modify the inner dictionary of the new dictionary, and verify that the original dictionary has not been modified.

gistlibby LogSnag