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

标签 python dictionary

首先,我创建了 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/

相关文章:

python - 如何将列表写入每行两个项目的文件

python - 在 Altair 中更改图例的大小

python - Django DRF 使用 CreateListModelMixin 更改序列化器数据

python - 将 csv 文件分配给字典集合(列表),其中文件名作为键,文件内容作为值

c# - C# 字典是否以与 Java HashMaps 相同的方式使用散列?

javascript - 在网页中创建交互式 map

java - 用于通过 ID 将数组索引到映射的通用类

python - scikit-learn 中的不平衡

python - 我们如何解压一个任意嵌套的迭代器、迭代器、[...]、迭代器?

Python:将列表排序为多个列表或字典