You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过可变路径参数修改Python嵌套字典的值?

如何传递字典路径参数修改嵌套字典并保存到JSON

你的问题核心是直接把路径字符串当作字典键来赋值,导致无法定位到嵌套的目标键。原代码中dictionary[target] = value会新增一个名为["key1"]["attribute1"]的键,而不是修改key1下的attribute1。下面给出两种实用的解决方法:

方法一:用*args传递路径的各个键(推荐)

这种方式不需要解析字符串,直接把路径的每一层键作为参数传递,直观且不易出错。

完整代码实现

import json

# 初始化JSON文件(仅第一次运行需要)
initial_dict = {
    'key1': {
        'attribute1': 'green',
    },
    'attribute2': 5
}
with open('savefile.json', 'w') as f:
    json.dump(initial_dict, f)

def SaveToFile(value, *path):
    # 读取JSON文件
    with open('savefile.json', 'r') as savefile:
        dictionary = json.load(savefile)
    
    # 逐层定位到目标键的父级字典
    current_level = dictionary
    for key in path[:-1]:
        current_level = current_level[key]
    # 修改目标键的值
    current_level[path[-1]] = value
    
    # 保存修改后的字典到JSON
    with open('savefile.json', 'w') as savefile:
        json.dump(dictionary, savefile)

# 调用示例:第一个参数是要设置的值,后面是路径的各个键
SaveToFile('blue', 'key1', 'attribute1')
SaveToFile(10, 'attribute2')

# 验证结果
with open('savefile.json', 'r') as f:
    result = json.load(f)
print(result)

输出结果

{
    "key1": {
        "attribute1": "blue"
    },
    "attribute2": 10
}

方法二:解析路径字符串(兼容你原有的调用方式)

如果坚持要用'["key1"]["attribute1"]'这种格式的字符串作为路径,可以通过正则提取其中的键,再逐层修改。

完整代码实现

import json
import re

# 初始化JSON文件(仅第一次运行需要)
initial_dict = {
    'key1': {
        'attribute1': 'green',
    },
    'attribute2': 5
}
with open('savefile.json', 'w') as f:
    json.dump(initial_dict, f)

def parse_path_str(path_str):
    # 用正则提取路径字符串中的所有键
    return re.findall(r'"([^"]+)"', path_str)

def SaveToFile(target, value):
    # 读取JSON文件
    with open('savefile.json', 'r') as savefile:
        dictionary = json.load(savefile)
    
    # 解析路径得到键列表
    path_keys = parse_path_str(target)
    # 逐层定位到目标键的父级字典
    current_level = dictionary
    for key in path_keys[:-1]:
        current_level = current_level[key]
    # 修改目标键的值
    current_level[path_keys[-1]] = value
    
    # 保存修改后的字典到JSON
    with open('savefile.json', 'w') as savefile:
        json.dump(dictionary, savefile)

# 调用示例:使用你原有的路径字符串格式
SaveToFile('["key1"]["attribute1"]', 'blue')
SaveToFile('["attribute2"]', 10)

# 验证结果
with open('savefile.json', 'r') as f:
    result = json.load(f)
print(result)

输出结果

和方法一一致,符合你的期望输出。


内容的提问来源于stack exchange,提问作者thelovedolphin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 22:55:18