虽然我认为 Martijn Pieters 的回答解决了他回答中的主要问题(您需要从递归案例中返回),但我认为他建议的代码不会正常工作。
rqfile
您正在尝试对嵌套dictionary
字典中的值进行深度优先搜索。但是您当前的代码没有正确处理递归情况。如果在其递归调用之一中找到结果,或者如果递归调用未能找到目标,它需要做出适当的响应。
这是我认为您需要的,为了清楚起见,对某些内容进行了重命名或重新排列:
def get_path(directory, rqfile, prefix=[]):
for filename, value in directory.items():
path_list = prefix + [filename]
if not isinstance(value, dict): # base case
path = os.path.join(*path_list)
if rqfile in path: # Found the file. Do you want to do something
return path # with the value here, or is it junk?
else: # recursive case
try:
return get_path(value, rqfile, path_list) # this only returns if
except ValueError: # the recursion doesn't raise
pass
raise ValueError("Requested file not found") # not found here or in children
示例用法:
>>> directory = {"a": "a info",
"b": {"c": "b/c info", "d": "b/d info"},
"e": {"f": "e/f info", "g": {"h": "e/g/h info"}}}
>>> print(get_path(directory, "h"))
e\g\h
>>> print(get_path(directory, r'g\h'))
e\g\h
如果您不想在找不到文件时引发异常,您还可以返回一个哨兵值None
代替最后一行,并在递归情况下检查哨兵值而不是try
/ except
:
result = get_path(value, rqfile, path)
if result is not None:
return result