递归地迭代嵌套的字典并返回第一个匹配键的值 [英] Recursively iterate through a nested dict and return value of the first matching key
问题描述
我有一个深层嵌套的dict,需要遍历它,并返回与 key
参数(函数的第二个参数)相对应的值。
I have a deeply nested dict and need to iterate through it and return the value corresponding to the key
argument, second argument of my function.
例如,使用
tree = {"a": 12, "g":{ "b": 2, "c": 4}, "d":5}
tree_traverse(tree, d)
应该返回5
这是我的代码:
def tree_traverse(tree, key):
for k,v in tree.items():
if isinstance(v, dict):
tree_traverse(v, key)
elif k == key:
return v
我遇到的问题是,一旦完成对最深层嵌套dict的迭代,该函数如果找不到匹配的键,则返回None。
在找到匹配密钥之前,我不希望它返回任何内容。
The problem I have is that this function returns None if it doesnt find the matching key once it's done iterating through the deepest nested dict. I don't want it to return anything before the matching key is found.
我没有在另一个线程中找到解决方案,其中大多数使用print语句并且不返回任何内容,所以我想它避免了这个问题。
I didn't find a solution in another thread, most of them use print statements and don't return anything so I guess it avoids this issue.
推荐答案
您必须检查递归调用是否确实找到了某些东西,以便您可以继续循环。例如。尝试以下操作:
You have to check whether the recursive call actually found something so you can continue the loop. E.g. try the following:
def tree_traverse(tree, key):
for k, v in tree.items():
if k == key:
return v
elif isinstance(v, dict):
found = tree_traverse(v, key)
if found is not None: # check if recursive call found it
return found
这篇关于递归地迭代嵌套的字典并返回第一个匹配键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!