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

如何通过嵌套路径更新字典?编写Python通用更新函数需求

实现嵌套字典路径值的通用更新函数

问题背景

现有如下字典:

{
  "person": {
    "name": "test_user"
  }
}

已知嵌套路径字符串 "person.name",需要编写一个通用函数 update_data,将该路径对应的值更新为 "test_user_2",执行后得到的结果应为:

{
  "person": {
    "name": "test_user_2"
  }
}

函数定义要求如下:

def update_data(data, nested_path, new_value):
    # 实现逻辑
    return new_data

解决方案

通过拆分路径、遍历层级并深拷贝原数据的方式实现通用更新,避免修改原始字典:

import copy

def update_data(data, nested_path, new_value):
    # 深拷贝原始数据,防止修改原对象
    new_data = copy.deepcopy(data)
    # 将路径按"."分割成键的列表
    keys = nested_path.split('.')
    # 遍历到倒数第二个键,定位到目标值的父层级
    current = new_data
    for key in keys[:-1]:
        current = current[key]
    # 更新最后一个键对应的值
    current[keys[-1]] = new_value
    return new_data

测试验证

# 原始数据
original_data = {
  "person": {
    "name": "test_user"
  }
}

# 调用更新函数
updated_data = update_data(original_data, "person.name", "test_user_2")

# 打印结果
print(updated_data)
# 输出:{'person': {'name': 'test_user_2'}}

# 验证原始数据未被修改
print(original_data)
# 输出:{'person': {'name': 'test_user'}}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 19:13:09