Assignment statements in Python do not copy objects, they create bindings between a target and an object.
dict2 = dict1, it results another binding between
dict2and the object that
dict1 refer to.
if you want to copy a dict, you can use the
The copy module has two interface:
copy.copy(x) Return a shallow copy of x. copy.deepcopy(x) Return a deep copy of x.
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.
For example, in python 2.7.9:
>>> import copy >>> a = [1,2,3,4,['a', 'b']] >>> b = a >>> c = copy.copy(a) >>> d = copy.deepcopy(a) >>> a.append(5) >>> a.append('c')
and the result is:
>>> a [1, 2, 3, 4, ['a', 'b', 'c'], 5] >>> b [1, 2, 3, 4, ['a', 'b', 'c'], 5] >>> c [1, 2, 3, 4, ['a', 'b', 'c']] >>> d [1, 2, 3, 4, ['a', 'b']]