在字典中递归查找键 [英] Finding a key recursively in a dictionary

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

问题描述

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

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

def _finditem(obj, key):如果键入 obj:返回 obj[key]对于 obj.items() 中的 k, v:如果 isinstance(v,dict):_finditem(v, 键)打印_finditem({"B":{"A":2}},"A")

它返回None.

然而,对于 _finditem({"B":1,"A":2},"A"),它确实有效,返回 2.

我确定这是一个简单的错误,但我找不到它.我觉得在标准库或 collections 中可能已经有一些东西,但我也找不到.

解决方案

递归时,需要return_finditem

的结果

def _finditem(obj, key):如果键入 obj:返回 obj[key]对于 obj.items() 中的 k, v:如果 isinstance(v,dict):return _finditem(v, key) #添加return语句

要修复实际算法,您需要意识到 _finditem 返回 None 如果没有找到任何内容,因此您需要明确检查以防止早期返回:

def _finditem(obj, key):如果键入 obj:返回 obj[key]对于 obj.items() 中的 k, v:如果 isinstance(v,dict):item = _finditem(v, key)如果项目不是无:归还物品

当然,如果您的任何字典中都有 None 值,这将失败.在这种情况下,你可以为这个函数设置一个哨兵 object() 并在你没有找到任何东西的情况下返回它 -- 然后你可以检查 sentinel 以了解您是否发现了某些东西.

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")

It returns None.

It does work, however, for _finditem({"B":1,"A":2},"A"), returning 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.

解决方案

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

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

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天全站免登陆