Martijn Pieters の回答は彼の回答の主要な問題に対処していると思いますが (再帰的なケースから戻る必要があります)、彼が提案したコードが正しく機能するとは思いません。
rqfile
ネストされたdictionary
dictの値に対して深さ優先検索を実装しようとしています。しかし、現在のコードは再帰的なケースを正しく処理していません。再帰呼び出しのいずれかで結果が見つかった場合、または再帰呼び出しでターゲットが見つからなかった場合は、適切に応答する必要があります。
明確にするために名前を変更したり、再配置したりして、必要なものをいくつか示します。
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