dict.copy()
Returns a new dictionary with the same keys and values. Adding keys to the copy leaves the original alone, but nested values stay shared.
dict.copy()b = a does not copy a dictionary; it gives the same dictionary a second name. a.copy() builds a separate dictionary with the same entries, so you can add, change or remove keys in one without touching the other.
The copy is shallow: the values themselves are not copied. If a value is a list or another dictionary, both copies hold that same object, and changing it inside shows up in both.
For dictionaries that contain lists or other dictionaries, use copy.deepcopy() when you need a fully independent copy.
Return value
A new dictionary with the same keys and values, in the same order.
Examples
1Copy, then change the copy
original = {"name": "Ana", "city": "Porto"}
copy_ = original.copy()
copy_["city"] = "Lisbon"
print(original)
print(copy_){'name': 'Ana', 'city': 'Porto'}
{'name': 'Ana', 'city': 'Lisbon'}2Assignment is not a copy
a = {"x": 1}
b = a
b["y"] = 2
print(a){'x': 1, 'y': 2}3The shallow-copy trap
team = {"name": "Blue", "members": ["Ben", "Dan"]}
clone = team.copy()
clone["members"].append("Eva")
clone["name"] = "Red"
print(team)
print(clone){'name': 'Blue', 'members': ['Ben', 'Dan', 'Eva']}
{'name': 'Red', 'members': ['Ben', 'Dan', 'Eva']}Replacing name only affects the copy, but appending to the shared members list changes both.
4A full copy with deepcopy()
import copy
team = {"name": "Blue", "members": ["Ben", "Dan"]}
clone = copy.deepcopy(team)
clone["members"].append("Eva")
print(team["members"])
print(clone["members"])['Ben', 'Dan'] ['Ben', 'Dan', 'Eva']
Common mistakes
Changing defaults by accident
If you start every user from the same defaults dictionary without copying it, each change ends up in the defaults. Copy first.
DEFAULTS = {"theme": "light"}
user1 = DEFAULTS
user1["theme"] = "dark"
print(DEFAULTS)
DEFAULTS = {"theme": "light"}
user2 = DEFAULTS.copy()
user2["theme"] = "dark"
print(DEFAULTS){'theme': 'dark'}
{'theme': 'light'}Questions people ask
How do I copy a dictionary in Python?
d.copy(), dict(d) or {**d} all make the same shallow copy. Use copy.deepcopy(d) when values are lists or dictionaries you will change.
What is the difference between copy() and deepcopy()?
copy() copies the dictionary but shares the values. deepcopy() also copies every nested list and dictionary.
Does copy() keep the key order?
Yes, the copy has the keys in the same order as the original.