How to copy a dictionary and only edit the copy

There are a few ways to copy a dictionary in Python, depending on the level of copying that you need.

The first way to make a copy of a dictionary is to use the built-in dict() function. This creates a shallow copy of the dictionary, which means that if the original dictionary contains any mutable objects (such as lists or other dictionaries), the copy will contain references to the same objects, rather than copies of those objects. Here's an example:

original_dict = {'a': [1, 2, 3], 'b': 4}
new_dict = dict(original_dict)

# Modifying original dict
original_dict['a'].append(4)
# Modifying new dict
new_dict['b'] = 6

print(original_dict)
# Output: {'a': [1, 2, 3, 4], 'b': 4}
print(new_dict)
# Output: {'a': [1, 2, 3, 4], 'b': 6}

Watch a course Python - The Practical Guide

Another way to copy a dictionary is to use the copy() method of the dictionary, like this:

original_dict = {'a': [1, 2, 3], 'b': 4}
new_dict = original_dict.copy()

# Modifying original dict
original_dict['a'].append(4)
# Modifying new dict
new_dict['b'] = 6

print(original_dict)
# Output: {'a': [1, 2, 3, 4], 'b': 4}
print(new_dict)
# Output: {'a': [1, 2, 3, 4], 'b': 6}

A third way to copy a dictionary is to use the built-in deepcopy() function from the copy module, like this:

import copy
original_dict = {'a': [1, 2, 3], 'b': 4}
new_dict = copy.deepcopy(original_dict)

# Modifying original dict
original_dict['a'].append(4)
# Modifying new dict
new_dict['b'] = 6

print(original_dict)
# Output: {'a': [1, 2, 3, 4], 'b': 4}
print(new_dict)
# Output: {'a': [1, 2, 3], 'b': 6}

This will create a deep copy of the dictionary, which means that if the original dictionary contains any mutable objects (such as lists or other dictionaries), those objects will also be copied, so that the copy is completely independent of the original.

In general, if you only have simple dictionary that has simple immutable types, then the dict() or copy() will work fine. But, if you have complex nested data structure in your dict or you want to ensure complete independence from the original object, use deepcopy.