使用词典时如何避免以下情况
a={'b':1}
c=a
c.update({'b':2})
print a # {'b':2}
print c # {'b':2}
Run Code Online (Sandbox Code Playgroud)
通过使用字典的copy方法。就像这样:
>>> a = {'b': 1}
>>> c = a.copy()
>>> c.update({'b': 2})
>>> print a
{'b': 1}
>>> print c
{'b': 2}
>>>
Run Code Online (Sandbox Code Playgroud)
请注意,这是一个浅拷贝。因此,如果字典中有可变对象(字典、列表等),它将复制对这些对象的引用。在这种情况下,您应该使用copy.deepcopy。下面的例子:
>>> import copy
>>> a = {'b': {'g': 4}}
>>> c = copy.deepcopy(a)
>>> c['b'].update({'g': 15})
>>> print a
{'b': {'g': 4}}
>>> print c
{'b': {'g': 15}}
Run Code Online (Sandbox Code Playgroud)