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

Python嵌套字典如何基于动态路径列表向指定层级追加新键值

实现方案

通用函数代码

def update_nested_dict(data, path, new_kv, create_missing=False):
    """
    动态定位嵌套字典节点并更新键值对
    :param data: 待修改的原始嵌套字典
    :param path: 路径列表,如 ['top_banner', 'image', 'global_image']
    :param new_kv: 要追加的键值对字典
    :param create_missing: 如果路径层级不存在,是否自动创建,默认False
    """
    current_node = data
    # 逐层遍历路径前置层级
    for key in path[:-1]:
        if create_missing and key not in current_node:
            current_node[key] = {}
        current_node = current_node[key]
    # 定位到目标节点后更新
    target_key = path[-1]
    if create_missing and target_key not in current_node:
        current_node[target_key] = {}
    current_node[target_key].update(new_kv)

使用示例

# 你的示例原始数据
data = {
  "top_banner": {
    "image": {
      "global_image": {
        "alt": " ",
        "src": "path/to/file/5473cd34fadbb6a3-dine-1.jpg",
        "sizes": [
          {
            "src": "",
            "view": "100vw",
            "media": "(min-width:100px)",
            "intrinsicwidth": 0,
            "intrinsicheight": 0
          }
        ],
        "types": [
          "webp ",
          "jpg"
        ],
        "background": True,
        "intrinsicWidth": 2400,
        "intrinsicHeight": 2400
      }
    },
    "title": "Dine",
    "description": ""
  }
}

# 示例路径
path = ['top_banner', 'image', 'global_image']
# 要追加/更新的键值对
new_attrs = {'intrinsicWidth': 200, 'intrinsicHeight': 300}

# 调用函数完成更新
update_nested_dict(data, path, new_attrs)

特性说明

  • 适配任意长度的路径列表,不管字典嵌套多少层都可以正常定位
  • 支持批量更新目标节点的多个键值对,update方法会自动覆盖已存在的键、新增不存在的键
  • 可选create_missing参数,开启后如果路径中某层字典不存在会自动创建空字典,避免抛出KeyError
  • 适配多路径批量处理场景,你示例中的嵌套路径列表直接循环调用即可:
path_list = [['top_banner', 'image', 'global_image'], ['other_path', 'level1', 'level2']]
for path in path_list:
    update_nested_dict(data, path, your_update_kv)

内容的提问来源于stack exchange,提问作者A l w a y s S u n n y

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:48:00