gpt4 book ai didi

python - 字典下的字典是按值复制而不是按引用复制?

转载 作者:行者123 更新时间:2023-12-01 05:30:43 25 4
gpt4 key购买 nike

首先,我创建了 xls_dictxml_dict

然后将上述两个字典包装到字典的创建中。 (我虽然是复制的,仅供引用)

所以我会将 json 文件加载到 2 个字典中。

但是,当我退出时我发现

对于 json_files.iteritems() 中的 export_file、data_dict: block 。

xls_dictxml_dict 未更改。

这不是我的预期。

我哪里理解错了?谢谢

    xls = MultiLangXls(xls_path, XLS_COLUMN)
xls_dict = xls.load()
xml = MultiLangXML(xml_path)
xml_dict = xml.load()

json_files={
"xls.json": xls_dict,
"xml.json": xml_dict
}

for export_file, data_dict in json_files.iteritems():
if os.path.isfile(export_file):
pass
else: # If json file not exists, then ouput the dict into json file
with open( export_file , 'w') as f:
json.dump(data_dict, f, encoding="utf-8")
load_file = open(export_file).read().decode("utf-8-sig")
data_dict = {}
data_dict = json.loads( load_file )

最佳答案

data_dict 变量确实引用同一个对象,而不是副本。然而,将一个新的字典分配给 data_dict 会断开该变量与该对象的连接,并为其分配一个全新的字典。

要清除现有字典,并用新内容填充它,您需要编写如下内容:

data_dict.clear()
data_dict.update(json.loads(load_file))

关于python - 字典下的字典是按值复制而不是按引用复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20344480/

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