嵌套字典copy()或deepcopy()?

时间:2016-09-13 16:34:40

标签: python dictionary copy deep-copy

我试图在代码的开头存储一个字典模板,大多数函数都会使用它:

  • 字典:keys =客户名称,值= Dictionary2
  • Dictionary2:keys =用户名,值=无

我填写了所有客户及其用户。然后代码的每个部分都可以复制这个字典并产生它拥有的输出。目标是每个输出都具有相同的基数"字典结构,如模板,其中无可修改。

对于使用此词典的每个进程,我使用以下内容:

process1dict = clientdict 
# processing 1
output1dict = ... #modified version of original clientdict, the None values have been replaced by dictionaries/lists

process2dict = clientdict
# processing 2
output2dict = ... #same here but could be different

我遇到的问题是cliendict每次复制到进程时都会改变! 我注意到,由于我的初始None中的cliendict值在每个进程后都会发生变化(当然,取决于每个进程的输出)。

修改:我找到了副本库但copy()似乎对我的情况没有帮助。我会尝试使用deepcopy(),但为什么copy()没有用?为什么deepcopy()会?

1 个答案:

答案 0 :(得分:4)

当您使用类似字典或列表的可变集合并执行赋值时,默认情况下您不创建该对象的副本 - 即,将某些字典b分配给另一个字典a创建了从b到原始对象a的引用,这样当你变异b时,你间接地也会改变a

请参阅此基本示例:

>>> orig = {"a": 1, "b": 2}
>>> new = orig
>>> new["a"] = 9
>>> orig
{'a': 9, 'b': 2}
>>> new
{'a': 9, 'b': 2}
>>> new is orig
True

要解决此问题,并将neworig词典分隔为彼此不引用的对象,请在将orig分配给new>>> import copy >>> orig = {"a": 1, "b": 2} >>> new = copy.deepcopy(orig) >>> new["a"] = 9 >>> orig {'a': 1, 'b': 2} >>> new {'a': 9, 'b': 2} >>> new is orig False }}:

def get_xpath_from_element(driver, element):
    return driver.execute_script("gPt=function(c){if(c.id!==''){return'id(\"'+c.id+'\")'}if(c===document.body){return c.tagName}var a=0;var e=c.parentNode.childNodes;for(var b=0;b<e.length;b++){var d=e[b];if(d===c){return gPt(c.parentNode)+'/'+c.tagName.toLowerCase()+'['+(a+1)+']'}if(d.nodeType===1&&d.tagName===c.tagName){a++}}};return gPt(arguments[0]);", element)

另外,这里是上面链接的Python文档的tl; dr:

  

Python中的赋值语句不复制对象,它们在目标和对象之间创建绑定。对于可变或包含可变项目的集合,有时需要一个副本,因此可以更改一个副本而不更改另一个副本。

相关问题