How do I deep copy dicts in Python in pure Python?

In Python, to create a deep copy of a dictionary, you can use the `copy` module, specifically the `deepcopy` function. This is useful when you want to duplicate an object and all objects it refers to, rather than just copying the references to those objects. Below is an example that demonstrates how to deep copy a dictionary.

import copy original_dict = { 'key1': 'value1', 'key2': ['list_item1', 'list_item2'], 'key3': {'nested_key1': 'nested_value1'} } # Create a deep copy of the original dictionary deep_copied_dict = copy.deepcopy(original_dict) # Modify the deep copied dictionary deep_copied_dict['key2'].append('list_item3') deep_copied_dict['key3']['nested_key1'] = 'modified_value' print("Original Dictionary:", original_dict) print("Deep Copied Dictionary:", deep_copied_dict)

deep copy dictionary Python copy module deepcopy data duplication