Python递归字典值查找函数返回None的问题排查与修复
递归查找字典键返回None的原因与修复
我正在处理多个不同深度的字典,需要在其中查找键"values"。尝试编写了递归函数,打印信息显示已找到目标键,但返回结果为None。
示例字典:
d = {'key1': {'key2': {'values': [0, 1, 2]}}}
编写的查找函数及输出:
def extract_key(dict_, key, path=[]): if not isinstance(dict_, dict): raise ValueError("went to deep") else: keys = list(dict_.keys()) # get all keys, list for indexing print("path:", path) print("keys:", keys) if key not in keys: # continue looking for key next_key = keys[0] print("next_key:", next_key) next_dict = dict_[next_key] # look with first key of keys path.append(next_key) extract_key(next_dict, key, path) else: # found key, return values print("out:", key) return dict_[key] output = extract_key(d, "values") print(output)
输出结果:
path: [] keys: ['key1'] next_key: key1 path: ['key1'] keys: ['key2'] next_key: key2 path: ['key1', 'key2'] keys: ['values'] out: values None
问题原因
- 递归调用未返回结果:当函数进入递归分支(
key not in keys)时,你调用了extract_key(next_dict, key, path)但没有将这个递归调用的返回值传递回去。外层的函数调用执行完这行代码后,没有任何return语句,因此默认返回None。 - 可变默认参数的隐患:
path=[]是可变对象,多次调用函数时会复用同一个列表,可能导致路径记录混乱。
修复方案
修改两处:
- 在递归调用时添加
return,将深层递归的结果返回给上层调用; - 把
path的默认参数改为None,在函数内部初始化空列表,避免可变默认参数的问题。
修复后的代码:
def extract_key(dict_, key, path=None): # 初始化path,避免可变默认参数的问题 if path is None: path = [] if not isinstance(dict_, dict): raise ValueError("went to deep") keys = list(dict_.keys()) print("path:", path) print("keys:", keys) if key not in keys: next_key = keys[0] print("next_key:", next_key) next_dict = dict_[next_key] path.append(next_key) # 添加return,将递归结果返回 return extract_key(next_dict, key, path) else: print("out:", key) return dict_[key] output = extract_key(d, "values") print(output)
运行后输出:
path: [] keys: ['key1'] next_key: key1 path: ['key1'] keys: ['key2'] next_key: key2 path: ['key1', 'key2'] keys: ['values'] out: values [0, 1, 2]
额外优化(可选)
如果你的字典可能有多个分支(不是只有第一个子键需要遍历),可以修改为遍历所有子键查找,而不是只取第一个:
def extract_key(dict_, key, path=None): if path is None: path = [] if not isinstance(dict_, dict): return None # 或者根据需求抛出异常 if key in dict_: print("out:", key) return dict_[key] # 遍历所有子键递归查找 for k, v in dict_.items(): result = extract_key(v, key, path + [k]) if result is not None: return result return None output = extract_key(d, "values") print(output)
内容的提问来源于stack exchange,提问作者Timo
相关产品推荐
相关产品推荐

