While difficult to access directly, python uses pointers under the hood.
How do you avoid this issue with shallow copies
import copy
original_dict = {
"name": "Alice",
"age": 25,
"skills": ["Python", "Data Science"],
"education": {
"degree": "Bachelor's",
"field": "Computer Science"
}
}
# Creating a shallow copy
shallow_copy = copy.copy(original_dict)
# modifying the original dictionary
original_dict["name"] = "Bob"
original_dict["education"]["degree"] = "Masters"
print(shallow_copy["education"]["degree"]) # This will return Masters!
The output is Masters, which is wrong.
?
Use deep copies
{python}deep_copy = copy.deepcopy(original_dict)