提问人:Alexey Kolosov 提问时间:3/29/2021 更新时间:3/29/2021 访问量:68
为什么 Python Dictionary 的行为类似于对象引用?[复制]
Why Python Dictionary behaves like object reference? [duplicate]
问:
我需要将 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
答:
0赞
Cyrille Pontvieux
3/29/2021
#1
通过这样做,您将获得对内部对象的引用(这里是字典)a["first"]
如果要在不影响初始字典的情况下修改字典,则必须显式创建一个新字典。有不同的方法可以做到这一点。您可以简单地执行以下操作:
x = dict(a["first"])
或
x = a["first"].copy()
下一个:递归的按值传递?
评论
python pass by reference
x = a["first"]
a["first"]
x = <whatever>
x
my_custom_map["first"]
shelve