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

嵌套字典中元素值的递归访问优化方法咨询

嵌套字典元素访问函数的改进方案

问题现状

当前实现的get_value_nested_dict函数仅支持Element直接位于SubKey下的场景,无法处理Element在SubKey子树任意深度的情况。例如调用get_value_nested_dict(nested_dict, 'dtc_all', '0x930001', 'identification')能正常返回结果,但调用get_value_nested_dict(nested_dict, 'dtc_all', '0x930001', 'udsDtcValue')无法获取到目标值。

改进思路

拆分搜索逻辑为两个独立阶段:

  • 定位阶段:递归遍历字典,找到MainKey对应的节点,再定位其下的SubKey子树
  • 全局搜索阶段:在SubKey的整个子树中递归搜索目标Element,无论其处于多少层深度

改进后的代码

Nested_Dict = {'candela_samples_generic': {'drc_dtcs': {'domain_name': 'TEMPLATE-DOMAIN', 'dtc_all': {'0x930001': {'identification': {'udsDtcValue': '0x9300', 'fault_type': '0x11', 'description': 'GNSS antenna short to ground'}, 'snapshots': {'snapshot_record_content': 'base', 'snapshot_records_numbers': ['0x01']}, 'functional_conditions': {'failure_name': 'short_to_ground', 'mnemonic': 'DTC_GNSS_Antenna_Short_to_ground'}}}}}}

def get_value_nested_dict(nested_dict, main_key, sub_key, element):
    results = []

    # 递归遍历SubKey子树,搜索任意深度的目标Element
    def search_element_in_subtree(subtree, target_element):
        if isinstance(subtree, dict):
            for k, v in subtree.items():
                if k == target_element:
                    results.append(v)
                search_element_in_subtree(v, target_element)

    # 递归定位MainKey节点,并找到其下的SubKey子树
    def locate_main_sub_key(current_dict):
        for key, value in current_dict.items():
            if key == main_key:
                if sub_key in value:
                    search_element_in_subtree(value[sub_key], element)
            if isinstance(value, dict):
                locate_main_sub_key(value)

    locate_main_sub_key(nested_dict)
    return results

# 测试验证
print(get_value_nested_dict(Nested_Dict, 'dtc_all', '0x930001', 'identification'))
# 输出: [{'udsDtcValue': '0x9300', 'fault_type': '0x11', 'description': 'GNSS antenna short to ground'}]
print(get_value_nested_dict(Nested_Dict, 'dtc_all', '0x930001', 'udsDtcValue'))
# 输出: ['0x9300']

关键改动说明

  • 拆分出两个职责单一的递归函数,避免原逻辑中参数传递冗余、职责混淆的问题
  • search_element_in_subtree会遍历SubKey下所有层级的节点,确保捕获到任意深度的目标Element
  • 逻辑分层清晰,定位阶段只负责找到目标子树,搜索阶段专注于全局匹配,提升代码可读性和可维护性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 12:43:21