在深度嵌套的字典中查找键 [英] Find a key inside a deeply nested dictionary
问题描述
我有很多嵌套的字典,我试图找到嵌套在某个地方的某个键.
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
.
这篇关于在深度嵌套的字典中查找键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!