问题描述
我需要使用 dict 中的 dict 作为副本,但是当我更改此副本时,原始 dict 也会更改。问题是:“是否有任何特定的文档来描述这种 Python 行为?”
b = {"first_first": 10} # internal dict
a = {"first": b,"second": 5} # full dict
print(a) # {'first': {'first_first': 10},'second': 5}
x = a["first"] # new object creation (want to get a copy of the internal dict)
x["first_first"] = 8 # created object modification
print(a) # {'first': {'first_first': 8},'second': 5} # Why was initial dict changed? Seems that
# line : x = a["first"] passes a reference
解决方法
通过执行 a["first"]
,您将获得对内部对象(这里是字典)的引用
如果你想在不影响初始字典的情况下修改字典,你必须明确地创建一个新字典。有不同的方法可以做到这一点。你可以简单地做:
x = dict(a["first"])
或
x = a["first"].copy()