在字典中递归地找到一个关键字 [英] Finding a key recursively in a dictionary

查看:114
本文介绍了在字典中递归地找到一个关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个非常简单的函数来递归搜索可能的嵌套(在最极端的情况下十级深)Python字典并返回从给定键找到的第一个值。

I'm trying to write a very simple function to recursively search through a possibly nested (in the most extreme cases ten levels deep) Python dictionary and return the first value it finds from the given key.

我不明白为什么我的代码不适用于嵌套字典。

I cannot understand why my code doesn't work for nested dictionaries.

def _finditem(obj, key):
    if key in obj: return obj[key]
    for k, v in obj.items():
        if isinstance(v,dict):
            _finditem(v, key)

print _finditem({"B":{"A":2}},"A")

它返回

然而,对于 _finditem({B:1,A:2},A),返回 2

我确定这是一个简单的错误,但我找不到。我觉得在标准库或集合中可能会有一些东西,但是我也找不到。

I'm sure it's a simple mistake but I cannot find it. I feel like there already might be something for this in the standard library or collections, but I can't find that either.

推荐答案

当您递归时,您需要返回 code> _finditem

when you recurse, you need to return the result of _finditem

def _finditem(obj, key):
    if key in obj: return obj[key]
    for k, v in obj.items():
        if isinstance(v,dict):
            return _finditem(v, key)  #added return statement

要修复实际算法,您需要意识到 _finditem 返回如果没有找到任何内容,那么您需要明确检查以防止提前返回:

To fix the actual algorithm, you need to realize that _finditem returns None if it didn't find anything, so you need to check that explicitly to prevent an early return:

def _finditem(obj, key):
    if key in obj: return obj[key]
    for k, v in obj.items():
        if isinstance(v,dict):
            item = _finditem(v, key)
            if item is not None:
                return item

当然,如果您的任何字典中都有 None 。在这种情况下,您可以为此函数设置哨兵 object(),并在没有找到任何内容的情况下返回 - 然后可以检查 sentinel 以了解您是否找到了某些东西。

Of course, that will fail if you have None values in any of your dictionaries. In that case, you could set up a sentinel object() for this function and return that in the case that you don't find anything -- Then you can check against the sentinel to know if you found something or not.

这篇关于在字典中递归地找到一个关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆