merge
dict.copy
Returns a shallow copy of the dictionary — a new dict object with the same key-value pairs. Values themselves are not copied, so nested mutable objects are still shared between the original and the copy.
d.copy() Parameters
| Parameter | Purpose |
|---|---|
| (no parameters) | copy takes no arguments |
| returns | New dict with the same key-value references |
Examples
>>> d = {'a': 1, 'b': 2}
>>> c = d.copy()
>>> c['a'] = 99
>>> d
{'a': 1, 'b': 2} Top-level mutations don't leak back
>>> d = {'x': [1, 2]}
>>> c = d.copy()
>>> c['x'].append(3)
>>> d
{'x': [1, 2, 3]} Shallow — nested list is shared. Use copy.deepcopy for full isolation
>>> d = {'a': 1}
>>> d.copy() is d
False Always a new object
>>> import copy
>>> d = {'x': [1, 2]}
>>> deep = copy.deepcopy(d)
>>> deep['x'].append(3)
>>> d
{'x': [1, 2]} Use copy.deepcopy when nested mutables must be independent
Gotcha
copy() is shallow — mutating nested lists/dicts affects both copies. Equivalent forms include dict(d) and {**d}; use copy.deepcopy(d) for a fully independent clone.
Related methods
dict.fromkeys
Class method that builds a new dict whose keys come from iterable and whose values are all set to value (default None). The same value object is shared across every key — beware mutable defaults.
dict.update
Updates the dictionary in place with key/value pairs from other, overwriting existing keys. Accepts another mapping, an iterable of key/value pairs, and/or keyword arguments; returns None.
dict1 | dict2
Merge operator (Python 3.9+) that returns a new dict containing the entries of d1 followed by d2, with d2's values winning on shared keys. Both operands must be dicts; neither is mutated.
dict1 |= dict2
In-place merge operator (Python 3.9+) that updates d1 with entries from other, with other's values winning on shared keys. Unlike |, the right operand can be any iterable of pairs or a mapping — matching update()'s flexibility.
← All Python dict methods · String methods · Built-in functions