编写高效Python函数:无需外部库按类CSS/XPath路径提取嵌套字典值
解决方案代码
先给出完整的getValue实现,满足所有需求:
test_dict = { "a": "1", "b": { "1": 2, "2": 4711, "3": { "b31": 31 }, "4": 4 }, "c": "3", "d": { "1": 5, "2": 9, "3": { "c31": 55 } } } test_result = 55 def getValue(nestedDict, key): # 解析路径为键列表,处理类似 "[d][3][c31]" 的格式 keys = [k.strip() for k in key.strip('[]').split('][')] def search(node, remaining_keys): # 递归搜索函数 if not remaining_keys: return node if not isinstance(node, dict): return None current_key = remaining_keys[0] # 先尝试当前层级直接匹配键 if current_key in node: result = search(node[current_key], remaining_keys[1:]) if result is not None: return result # 当前层级没有匹配,遍历所有子字典继续搜索(支持相对路径) for value in node.values(): if isinstance(value, dict): result = search(value, remaining_keys) if result is not None: return result return None return search(nestedDict, keys) if __name__ == '__main__': result = getValue(test_dict, "[3][c31]") # 返回55 result2 = getValue(test_dict, "[d][3][c31]") # 返回55 assert result == test_result print(result)
代码说明
- 路径解析:通过字符串处理把
[key1][key2]格式的路径拆分成键列表,无需依赖正则库,简洁高效。 - 递归搜索逻辑:
- 优先从当前层级匹配路径的第一个键,匹配成功则继续深入下一层路径。
- 当前层级无匹配时,遍历所有子字典递归搜索,实现相对路径支持——无需指定完整绝对路径,只要嵌套结构中存在符合路径的键链就能找到值。
- 找到第一个匹配结果立即返回,避免不必要的遍历;任何环节不匹配则返回
None。
- 无外部依赖:完全基于Python内置类型和函数实现,符合需求。
递归 vs 循环的效率对比
- 递归的局限:Python有默认递归深度限制(默认1000层),如果嵌套字典深度超过该值,会直接抛出
RecursionError;且每次递归调用会创建栈帧,带来额外内存和性能开销。 - 循环的优势:循环实现无递归深度限制,且无栈帧开销,在嵌套深度大、数据量多的场景下,效率明显更高。
- 结论:若嵌套字典深度可能较大,优先选循环实现;若深度可控,递归代码可读性更好,但效率不如循环。
附循环版本实现(供参考):
def getValue_loop(nestedDict, key): keys = [k.strip() for k in key.strip('[]').split('][')] # 用队列保存待搜索的节点和剩余路径 queue = [(nestedDict, keys)] while queue: node, remaining = queue.pop(0) if not remaining: return node if not isinstance(node, dict): continue current_key = remaining[0] if current_key in node: queue.append((node[current_key], remaining[1:])) # 遍历子字典加入队列 for value in node.values(): if isinstance(value, dict): queue.append((value, remaining)) return None
内容的提问来源于stack exchange,提问作者DevArchitectMaster
相关产品推荐
相关产品推荐

