求助:实现递归搜索字典并返回键路径的Python函数
问题描述
现有如下嵌套字典数据:
data = { "A_level_1":{ "A_level_2":{ "A_level_3":{ "A_level_4":"some value" } }, "B_level_2":{ "B_level_3":{ "B_level_4":{ "B_level_5":"some value" } } } } }
目前仅完成了如下不完整的代码:
def find(search_dict, path): for key, value in search_dict.items(): if isinstance(value, dict): find(value, key+".")
需要实现一个函数,接收字典和目标键作为参数,返回以点分隔的嵌套键完整路径。预期调用结果如下:
find(data,"A_level_3"):A_level_1.A_level_2.A_level_3find(data,"B_level_3"):A_level_1.B_level_2.B_level_3find(data,"B_level_5"):A_level_1.B_level_2.B_level_3.B_level_4.B_level_5
实现方案
通过递归遍历字典并跟踪当前路径,匹配到目标键时返回完整路径即可。完整代码如下:
def find(search_dict, target_key, current_path=""): for key, value in search_dict.items(): # 拼接当前路径,根节点路径直接用键名 new_path = f"{current_path}.{key}" if current_path else key # 匹配到目标键,直接返回完整路径 if key == target_key: return new_path # 当前值是字典时,递归遍历子节点 if isinstance(value, dict): result = find(value, target_key, new_path) # 递归找到结果就返回,无需继续遍历 if result is not None: return result # 遍历完所有节点未找到目标键,返回None return None
代码说明
- 路径跟踪:新增
current_path参数默认空字符串,用来记录遍历过程中的当前路径。 - 路径拼接:根节点直接用键名作为初始路径,后续节点在现有路径后追加
.键名。 - 递归逻辑:遇到子字典时递归调用函数,若递归返回有效结果则直接返回,避免无效遍历。
- 未找到处理:遍历完所有节点仍未匹配到目标键时,返回
None。
测试验证
调用示例:
data = { "A_level_1":{ "A_level_2":{ "A_level_3":{ "A_level_4":"some value" } }, "B_level_2":{ "B_level_3":{ "B_level_4":{ "B_level_5":"some value" } } } } } print(find(data,"A_level_3")) # 输出: A_level_1.A_level_2.A_level_3 print(find(data,"B_level_3")) # 输出: A_level_1.B_level_2.B_level_3 print(find(data,"B_level_5")) # 输出: A_level_1.B_level_2.B_level_3.B_level_4.B_level_5
内容的提问来源于stack exchange,提问作者Romillion
相关产品推荐
相关产品推荐

