Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Python dict.copy() method

Reference for Python dict.copy(): create a shallow copy of a dictionary, why nested values are shared, and when to use copy.deepcopy() or dict(d) instead.

The dict.copy() method returns a new dictionary with the same keys and values as the original. Adding, removing or replacing entries in the copy does not affect the original, and the other way round.

The copy is shallow: it copies the references to the values, not the values themselves. If a value is a mutable object such as a list or another dictionary, both dictionaries refer to that one object, and changing it through one dictionary is visible through the other.

Python
a = {"x": 1}
b = a.copy()
b["x"] = 2
print(a, b)   # {'x': 1} {'x': 2}

Try it

Python An independent top level

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Shallow versus deep

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
dict.copy()

copy() takes no arguments.

Return value: a new dict with the same key-value pairs and the same insertion order.

Raises: nothing.

Usage notes

  • Shallow only. Nested lists, sets, dicts and other mutable values are shared. For fully independent data use copy.deepcopy().
  • Assignment is not copying. b = a creates a second name for the same dictionary. Use copy() to get a separate one.
  • Equivalent forms. dict(d) and {**d} produce the same shallow copy. copy() is the most explicit.
  • Subclasses. On a plain dict, the result is a plain dict. collections.OrderedDict.copy() and defaultdict.copy() keep their own types. A custom subclass may return a plain dict from dict.copy() unless it overrides it, so check if you rely on the type.
  • Immutable values are safe. If all values are numbers, strings or tuples of those, a shallow copy behaves like a deep one.
  • Cost. Copying takes time proportional to the number of entries. Do not copy inside a hot loop if a view or iteration would do.
  • Merging instead. To copy and change at once, use d | {"key": value} (Python 3.9+) or {**d, "key": value}.