A settings screen needs an editable copy of defaults.
What You Need to Understand
dict.copy() produces a shallow copy of the mapping: the outer dictionary is new, but referenced nested values are shared.
When to Use It
A settings screen needs an editable copy of defaults.
Step-by-Step Python Example
defaults = {"theme": "light", "size": 12}
custom = defaults.copy()
custom["theme"] = "dark"
print(defaults)
print(custom)
How the Example Works
Changing a top-level key in the copy does not change that key in the original.
Example Output
{'theme': 'light', 'size': 12}
{'theme': 'dark', 'size': 12}
{'a': [1, 2]}
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
original = {"a": [1]}
copy_of_original = original.copy()
copy_of_original["a"].append(2)
print(original)
Important Behavior and Edge Cases
Nested dictionaries and lists remain shared by shallow copies; use copy.deepcopy() if true nested independence is required.
Try It Yourself
Copy an inventory dictionary and add a new product to the copy.
Common Beginner Mistakes
- Nested dictionaries and lists remain shared by shallow copies; use
copy.deepcopy()if true nested independence is required. - Using the wrong collection method for this operation without checking whether it mutates the object, returns a result, or raises on missing data.
Key Takeaways
dict.copy()produces a shallow copy of the mapping: the outer dictionary is new, but referenced nested values are shared.- Changing a top-level key in the copy does not change that key in the original.
- Nested dictionaries and lists remain shared by shallow copies; use
copy.deepcopy()if true nested independence is required.