Junior — Middle
How can you create an exact copy of a dictionary in Python?
sobes.tech AI
Answer from AI
In Python, there are several ways to create a deep copy of a dictionary:
- The
copy()method of a dictionary — creates a shallow copy:
original = {'a': 1, 'b': 2}
copied = original.copy()
- The
dict()function — creates a new dictionary from an existing one:
copied = dict(original)
- The
copymodule with thedeepcopy()function — if the dictionary contains nested mutable objects and a deep copy is needed:
import copy
copied = copy.deepcopy(original)
If the dictionary contains only simple types (numbers, strings), then copy() or dict() is sufficient. If there are nested structures (lists, other dictionaries), and you need to copy them as well, use deepcopy().