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

Python中通过键树数组动态获取并修改字典值的方法

动态通过键树数组获取并修改嵌套结构的值

核心思路

要实现这个需求,关键是遍历key_tree逐步定位到目标值的父容器(可能是列表或字典),以及目标值对应的最后一个键/索引——因为直接修改值本身无法影响原结构,必须操作它所在的父容器。

实现代码

person_dict = [{"person": {"first_name": "John", "age_of_children": [1, 8, 13]}}]

def access_and_update(data, key_tree, new_value=None):
    # 遍历键树的前n-1个元素,定位到目标值的父容器
    current_container = data
    for key in key_tree[:-1]:
        current_container = current_container[key]
    
    # 获取目标值的直接键/索引
    target_key = key_tree[-1]
    
    # 如果传入新值则修改,同时返回修改前的旧值
    if new_value is not None:
        old_value = current_container[target_key]
        current_container[target_key] = new_value
        return old_value
    # 未传入新值则仅返回当前值
    return current_container[target_key]

# 示例1:修改first_name
key_tree1 = [0, "person", "first_name"]
old_name = access_and_update(person_dict, key_tree1, "Jane")
print(old_name)  # 输出: John
print(person_dict)  # 输出: [{"person": {"first_name": "Jane", "age_of_children": [1, 8, 13]}}]

# 示例2:修改age_of_children数组
key_tree2 = [0, "person", "age_of_children"]
old_ages = access_and_update(person_dict, key_tree2, [2, 9, 14])
print(old_ages)  # 输出: [1, 8, 13]
print(person_dict)  # 输出: [{"person": {"first_name": "Jane", "age_of_children": [2, 9, 14]}}]

# 示例3:仅获取值不修改
key_tree3 = [0, "person", "first_name"]
current_name = access_and_update(person_dict, key_tree3)
print(current_name)  # 输出: Jane

细节说明

  • 兼容列表与字典:不管父容器是列表(用数字索引)还是字典(用字符串键),current_container[key]的语法都能正常工作,无需额外判断。
  • 灵活操作:通过new_value参数控制是仅读取值还是同时修改,满足两种场景需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 14:12:26