How to copy a dictionary and only edit the copy How to copy a dictionary and only edit the copy python python

How to copy a dictionary and only edit the copy


Python never implicitly copies objects. When you set dict2 = dict1, you are making them refer to the same exact dict object, so when you mutate it, all references to it keep referring to the object in its current state.

If you want to copy the dict (which is rare), you have to do so explicitly with

dict2 = dict(dict1)

or

dict2 = dict1.copy()


When you assign dict2 = dict1, you are not making a copy of dict1, it results in dict2 being just another name for dict1.

To copy the mutable types like dictionaries, use copy / deepcopy of the copy module.

import copydict2 = copy.deepcopy(dict1)


While dict.copy() and dict(dict1) generates a copy, they are only shallow copies. If you want a deep copy, copy.deepcopy(dict1) is required. An example:

>>> source = {'a': 1, 'b': {'m': 4, 'n': 5, 'o': 6}, 'c': 3}>>> copy1 = x.copy()>>> copy2 = dict(x)>>> import copy>>> copy3 = copy.deepcopy(x)>>> source['a'] = 10  # a change to first-level properties won't affect copies>>> source{'a': 10, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}>>> copy1{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}>>> copy2{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}>>> copy3{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}>>> source['b']['m'] = 40  # a change to deep properties WILL affect shallow copies 'b.m' property>>> source{'a': 10, 'c': 3, 'b': {'m': 40, 'o': 6, 'n': 5}}>>> copy1{'a': 1, 'c': 3, 'b': {'m': 40, 'o': 6, 'n': 5}}>>> copy2{'a': 1, 'c': 3, 'b': {'m': 40, 'o': 6, 'n': 5}}>>> copy3  # Deep copy's 'b.m' property is unaffected{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}

Regarding shallow vs deep copies, from the Python copy module docs:

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.