Shallow vs Deep Copy of Nested Dicts

Medium ⏱ 12 min 64% acceptance ★★★★★ 4.9
Write a function deep_copy_dict(d) that returns a deep copy of a (possibly nested) dict d, such that mutating a nested dict or list inside the copy never affects the original. Use copy.deepcopy.

Examples

Example 1
Input
orig = {'a': {'b': 1}}; c = deep_copy_dict(orig); c['a']['b'] = 99; orig['a']['b']
Output
1
Explanation

Mutating the deep copy leaves the original untouched.

Constraints

  • d may contain nested dicts and lists.
  • Must use the `copy` module.

Topics

Dictionariescopying

Companies

SalesforceServiceNow

Hints

Hint 1

`import copy` then `return copy.deepcopy(d)`.

Hint 2

Contrast with `dict(d)` or `d.copy()`, which only copy one level (shallow copy).

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.