最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】python中的dict被copy后仍会被修改

Python crifan 5067浏览 0评论

折腾:

【已解决】Python中实现dict的递归的合并更新

期间,遇到了:一个dict被copy后,结果传递到一个函数中,结果外面的,原先的dict还是被修改了值。

然后用:

<code>
def recursiveMergeDict(originalDict, toMergeDict):
    """
    Recursively merge origin and to merge dict, return merged dict.
    Sub dict's won't be overwritten but also updated.
    """
    originalDictItems = None
    if (sys.version_info[0] == 2): # is python 2
      originalDictItems = originalDict.iteritems()
    else: # is python 3
      originalDictItems = originalDict.items()

    for key, value in originalDictItems:
      if key not in toMergeDict:
          toMergeDict[key] = value
      elif isinstance(value, dict):
          recursiveMergeDict(value, toMergeDict[key])

    return toMergeDict
</code>

调用:

<code>bookJson = recursiveMergeDict(templateJson, currentJson.copy())
</code>

或:

<code>bookJson = currentJson.copy()
recursiveMergeDict(templateJson, bookJson)
</code>

都还是会修改掉dict:currentJson

所以去搞清楚:

python dict copy deepcopy

Deep copy of a dict in python – Stack Overflow

python – Understanding dict.copy() – shallow or deep? – Stack Overflow

8.17. copy — Shallow and deep copy operations — Python 2.7.15 documentation

Be careful with using dict() to create a copy – Peterbe.com

试试:

<code>bookJson = recursiveMergeDict(templateJson, copy.deepcopy(currentJson))
</code>

结果是可以的。

原先的dict不会被修改。

【总结】

python中的dict,如果是:

<code>copiedDict = originDict.copy()
</code>

则根据:

8.17. copy — Shallow and deep copy operations — Python 2.7.15 documentation

copiedDict是叫做shallow copy,影子拷贝

-》类似于C语言的指针

-〉修改了copiedDict,原先的originDict也同时被修改

而想要脱离关系,则需要用到深度拷贝

<code>import copy
deepCopiedDict = copy.deepcopy(originDict)
</code>

则deepCopiedDict和originDict就没有关系了。

修改deepCopiedDict,不会影响到originDict。

转载请注明:在路上 » 【已解决】python中的dict被copy后仍会被修改

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.184 seconds, using 22.05MB memory