Pythonic更新json dict中存储的多个值的方法
我有一个json文件,其中存储了一个值字典。我知道如何单独修改键的值,但我想知道如何使用另一个字典更新json文件中的字典 json文件名为'dummy.json'Pythonic更新json dict中存储的多个值的方法,python,json,dictionary,Python,Json,Dictionary,我有一个json文件,其中存储了一个值字典。我知道如何单独修改键的值,但我想知道如何使用另一个字典更新json文件中的字典 json文件名为'dummy.json' { "my_settings": { "volts": "21.8", "power": "25.8", "current": "1.0"
{
"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"
}
}
代码:
结果:
{
"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"
}
}
update(dict_设置)将使用dict_设置中的所有值对json_数据字典进行udpate。然后把它写回文件。如果我理解了这个问题,我想它会满足你的要求。试试
。更新(new\u dict)
这会有用的。我不确定我把它放在哪里了,我会试试一些东西。太好了,谢谢
{
"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"
}
}