【问题标题】:Pythonic way to update multiple values stored within a json dict更新存储在 json dict 中的多个值的 Pythonic 方法
【发布时间】:2021-05-27 07:28:00
【问题描述】:

我有一个 json 文件,其中存储了一个值字典。我知道如何单独修改一个键的值,但我想知道如何用另一个字典更新 json 文件中的字典。

名为“dummy.json”的 json 文件

{
    "my_settings": {
        "volts": "21.8",
        "power": "25.8",
        "current": "1.0",
        "time_on": 88888.0,
        "time_off": "1.5",
        "week": 444,
        "site": 4,
        "op": "ABC",
        "test": "Ubik",
        "repeats": 7,
        "freq": "6000",
        "SN": "3",
        "Vpeak": 27.5,
        "Vrms": 26.8,
        "Foobar": "True"
    }
}

代码

json_file = 'dummy.json'

def modify_json_file(json_file, settings_dict, settings_dict_key, new_dict_value):
    with open(json_file, "r") as input_json:
        json_data = json.load(input_json)
        dict_to_modify = json_data[settings_dict]
    dict_to_modify[settings_dict_key] = new_dict_value
    with open(json_file, "w") as input_json:
        json_data[settings_dict]=dict_to_modify
        json_data = json.dump(json_data, input_json, indent = 4)

modify_json_file(json_file, "my_settings", "week", 444) # works

我想用来更新 dummy.json 的新字典

new_data = {"volts": 20.0,
        "power": 11.1,
        "current": 2.2}

期望的输出

{
    "my_settings": {
        "volts": 20.0,
        "power": 11.1,
        "current": 2.2,
        "time_on": 88888.0,
        "time_off": "1.5",
        "week": 444,
        "site": 4,
        "op": "ABC",
        "test": "Ubik",
        "repeats": 7,
        "freq": "6000",
        "SN": "3",
        "Vpeak": 27.5,
        "Vrms": 26.8,
        "Foobar": "True"
    }
}

【问题讨论】:

  • json_data.update(dict_settings) 将使用 dict_settings 中的所有值更新 json_data 字典。然后将其写回文件中。如果我理解这个问题,我认为它会满足你的要求。
  • 试试.update(new_dict) 这会奏效..
  • 我不确定我把它放在哪里,我会尝试一些东西。

标签: python json dictionary


【解决方案1】:

代码:

import json
json_file = 'dummy.json'

def update_json_file(json_file,new_dict,key_name):
    with open(json_file, "r+") as input_json:
        json_data = json.load(input_json)
        json_data[key_name].update(new_dict[key_name])
        input_json.seek(0)
        json.dump(json_data, input_json, indent = 4)
        input_json.truncate()

new_dict = {"my_settings":{"volts": 20.0,"power": 11.1,"current": 2.2}}
update_json_file(json_file,new_dict,"my_settings")

结果:

{
    "my_settings": {
        "volts": 20.0,
        "power": 11.1,
        "current": 2.2,
        "time_on": 88888.0,
        "time_off": "1.5",
        "week": 444,
        "site": 4,
        "op": "ABC",
        "test": "Ubik",
        "repeats": 7,
        "freq": "6000",
        "SN": "3",
        "Vpeak": 27.5,
        "Vrms": 26.8,
        "Foobar": "True"
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2017-06-07
    • 2018-06-02
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多