gpt4 book ai didi

python - 创建嵌套字典的副本而不是引用

转载 作者:行者123 更新时间:2023-12-02 21:17:18 27 4
gpt4 key购买 nike

为什么使用dict()函数不会像标准键:值对字典那样创建带有嵌套字典的副本?

字典

A = {'key' : 'value'}
B = dict(A)
A['key'] = 10
print A, B

输出:

{'key': 10} {'key': 'value'}

嵌套字典:

A = {'key' : {'subkey' : 'value'}}
B = dict(A)
A['key']['subkey'] = 10
print A, B

输出:

{'key': {'subkey': 10}} {'key': {'subkey': 10}}

最佳答案

您需要创建一个 deepcopy :

from copy import deepcopy
A = {'key' : {'subkey' : 'value'}}
B = deepcopy(A)
A['key']['subkey'] = 10
print(A, B)
# {'key': {'subkey': 10}} {'key': {'subkey': 'value'}}

关于python - 创建嵌套字典的副本而不是引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29855211/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com