Why did changing a copied dict also change the original?
Question
This code builds one user's settings from shared defaults. After it runs, every new user also gets the lint plugin.
What does print(defaults) show? Why did the plugins edit reach defaults when the theme edit didn't? Then fix the code so that changes to settings never reach defaults.
defaults = {"theme": "light", "plugins": ["git"]}
settings = defaults.copy()
settings["theme"] = "dark"
settings["plugins"].append("lint")
print(defaults)Show hints (3)
- "TWO KINDS OF EDIT"
settings["theme"] = "dark"puts a new value intosettings.settings["plugins"].append("lint")changes an object stored inside it. Which of the two coulddefaultsalso see? - "SAME LIST?"
Add
print(settings["plugins"] is defaults["plugins"])right after the copy. It printsTrue. What does that tell you about.copy()? - "COPY DEEPER"
.copy()copies only the outer dict. You also need a new list. Usecopy.deepcopy(defaults), or copy the outer dict and the list you will change.
Show checked explanation
It prints {'theme': 'light', 'plugins': ['git', 'lint']}. dict.copy() makes a shallow copy: a new outer dict that holds the same plugins list. Setting theme changes only the copy, but append changes the shared list. Fix it with copy.deepcopy(defaults), or copy the nested list yourself.
import copy defaults = {"theme": "light", "plugins": ["git"]} settings = copy.deepcopy(defaults) settings["theme"] = "dark" settings["plugins"].append("lint") print(defaults) print(settings) print(settings["plugins"] is defaults["plugins"])
{'theme': 'light', 'plugins': ['git']}
{'theme': 'dark', 'plugins': ['git', 'lint']}
FalseCode run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
The starter prints {'theme': 'light', 'plugins': ['git', 'lint']}. The theme change stayed in the copy. The plugin change reached defaults too.
Track the objects, not the names. After settings = defaults.copy() there are two dicts but only one list:
| name | dict | "plugins" refers to |
|---|---|---|
defaults | dict A | list L |
settings | dict B | list L |
A shallow copy makes a new outer container, but puts the same objects inside it. Now look at the two edits:
settings["theme"] = "dark"stores a new value in dict B. Dict A still holds"light".settings["plugins"].append("lint")first gets list L, then changes it in place. Both dicts hold L, so both show['git', 'lint'].
So assigning to a key changes only that one dict. Methods like append, extend, sort and update work differently. They change the object itself, in place. Every name and every container that holds that object sees the change.
copy.deepcopy copies the nested lists and dicts too. After it, settings["plugins"] is defaults["plugins"] is False, so append only touches the copy. Strings and numbers are not copied. That is safe, because they can't be changed in place.
You don't always need a full deep copy. If only the plugin list will change, copy just that level:
settings = {**defaults, "plugins": list(defaults["plugins"])}This is cheap and shows exactly which parts are separate. But every nested field you change must be copied this way. Forget one, and the shared-list bug is back.
Common mistakes
- Expecting
dict(x),{**x},copy.copy(x),list(x)orx[:]to copy nested data. Like.copy(), they all copy only the outer container. - Using
settings = defaultsas a copy. That is a second name for the same dict, so evensettings["theme"] = "dark"changesdefaults. - Thinking a tuple protects what is inside it. In
pair = ("git", ["lint"])you can't replacepair[1], butpair[1].append("test")still changes the list. - Expecting
del defaultsto delete the dict.delremoves only the name. If another name still refers to the dict, or a shallow copy shares its list, those objects stay alive and can still change.
Follow-up questions
- "Two keys share one list:
board = {"left": shared, "right": shared}. Aftercopy.deepcopy(board), can you change one side without the other?" No.deepcopyremembers what it has already copied. So it copies the shared list once, and both keys get that one copy. Withshared = ["todo"], appending"done"to the copy's"left"list also shows in its"right"list.sharedstays["todo"]. To keep the sides apart, give each key its ownlist(shared). - "Is
deepcopyalways the right fix?" No. It goes through every nested object, which is slow for large data. Some objects can't be deep-copied at all: athreading.LockraisesTypeError. An open file or ansqlite3connection fails the same way, and you wouldn't want two of them anyway. Often it's better to copy only the parts you will change.
What a strong answer covers
Names shallow and deep copy. Explains why assigning a key and calling append act on different objects, and proves the sharing with is. Can copy just the part that will change, and knows that deepcopy keeps shared parts shared.
Open in interactive practice deck →