【问题标题】:如何在python中将多个字典添加到一个json文件中?
【发布时间】:2022-01-23 14:20:57
【问题描述】:

如何在 JSON 文件中添加多个字典? 我想在同一个 JSON 文件中添加 1 个或 2 个字典,并在一段时间后添加 1 个或 2 个或 3 个字典。

示例:

 dict1 = {'a': 1, 'b':2}

-> 我想将它添加到一个 'test.json' 文件中,过一会儿我想添加字典

 dict2 = {'c': 1, 'd':2}
 dict3 = {'e': 1, 'f':2}

-> 过了一会儿我想添加这个 2 例如

编辑

import json
dict1 = {'a': 1, 'b': 1}
dict2 = {'c': 2, 'd': 2}
dict3 = {'e': 3, 'f': 3}
list1 = []
list1.append(dict1)
with open('testjson_dict.json', 'a') as f:
    json.dump(list1, f)

->这是第一个输出

[
    {
        "a": 1,
        "b": 1
    }
]

-> 我将 dict2 附加到 list1,这是输出,它创建第二个列表并将 dict2 放入其中,我如何更改代码以将 dict2 放入我的第一个列表中?

[
    {
        "a": 1,
        "b": 1
    }
][
    {
        "c": 2,
        "d": 2
    }
]

【问题讨论】:

    标签: python json dictionary add


    【解决方案1】:

    我假设您想将这些字典存储为 json 中的列表,因此最终结果将是:

    [
      {'a': 1, 'b':2}, 
      {'c': 1, 'd':2}, 
      {'e': 1, 'f':2}
    ]
    

    这是一个可能的工作流程。以dict_list = [dict1]开头。

    1. 确保您import json。将dict_list 写入test.json
        with open('test.json', 'w', encoding='utf-8') as json_file:
            json.dump(dict_list, json_file)
    
    1. test.json 的内容读入 Python 列表。
        with open('test.json', encoding='utf-8') as json_file:
            dicts = json.load(json_file)
    
    1. dict2dict3 添加到您刚刚读入的列表中。
    2. 用结果列表覆盖test.json(如步骤1)。

    现在test.json 应该包含 3 个字典的列表。

    【讨论】:

      【解决方案2】:

      您可以通过这种方式将新数据连接为带有 + 的列表:

      import json
      # write first file
      dict_list = [{'a': 1, 'b':2}]
      with open('test.json', 'w', encoding='utf-8') as json_file:
          json.dump(dict_list, json_file)
      
      # concat to readed file and overvwrite
      with open('test.json', encoding='utf-8') as json_file:
          dicts = json.load(json_file)
      dicts += [{'c': 1, 'd':2}, {'e': 1, 'f':2}] # list concatenation operation
      with open('test.json', 'w', encoding='utf-8') as json_file:
          json.dump(dicts, json_file)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-16
        • 2015-03-21
        • 1970-01-01
        • 2017-04-10
        • 2022-07-10
        • 2018-05-14
        相关资源
        最近更新 更多