How to copy a dictionary and only edit the copy

前端 未结 20 1977
说谎
说谎 2020-11-21 06:59

Can someone please explain this to me? This doesn\'t make any sense to me.

I copy a dictionary into another and edit the second and both are changed. Why is this hap

20条回答
  •  情深已故
    2020-11-21 07:44

    Assignment statements in Python do not copy objects, they create bindings between a target and an object.

    so, 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 copy module. 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[4].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']]
    

提交回复
热议问题