在深度嵌套的字典中查找键

编程入门 行业动态 更新时间:2024-10-24 02:01:01
本文介绍了在深度嵌套的字典中查找键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有很多嵌套的字典,我试图找到嵌套在某个地方的某个键.

I have a lot of nested dictionaries, I am trying to find a certain key nested inside somewhere.

例如此键称为水果".如何找到此键的值?

e.g. this key is called "fruit". How do I find the value of this key?

推荐答案

@Håvard的递归解决方案可能会好起来的……除非嵌套级别太高,然后得到RuntimeError: maximum recursion depth exceeded.为了解决这个问题,您可以使用递归删除的常用技术:保留您自己要检查的项目堆栈(作为您控制下的列表).即:

@Håvard's recursive solution is probably going to be OK... unless the level of nesting is too high, and then you get a RuntimeError: maximum recursion depth exceeded. To remedy that, you can use the usual technique for recursion removal: keep your own stack of items to examine (as a list that's under your control). I.e.:

def find_key_nonrecursive(adict, key): stack = [adict] while stack: d = stack.pop() if key in d: return d[key] for k, v in d.iteritems(): if isinstance(v, dict): stack.append(v)

这里的逻辑与递归答案非常接近(除了以正确的方式检查dict ;-),明显的例外是递归调用被while循环和.pop替换,并且.append在显式堆栈列表stack上的操作.

The logic here is quite close to the recursive answer (except for checking for dict in the right way;-), with the obvious exception that the recursive calls are replaced with a while loop and .pop and .append operations on the explicit-stack list, stack.

更多推荐

在深度嵌套的字典中查找键

本文发布于:2023-11-12 03:44:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580417.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   字典   深度

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!