且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

递归地迭代嵌套的字典并返回第一个匹配键的值

更新时间:2023-02-19 11:34:46

您必须检查递归调用是否确实找到了某些东西,以便您可以继续循环。例如。尝试以下操作:

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