假设我有一个python字典,很多巢 [英] Suppose I have a python dictionary , many nests
问题描述
如果有很多嵌套字典,我试图找到一个特定的键。
If a lot of nested dictionarys, I am trying to find a certain key.
这个键叫做水果。但它嵌套在某个地方。如何找到这个密钥的值?
this key is called "fruit". But it's nested inside somewhere. How do I find the value of this key?
推荐答案
@Håvard的递归解决方案可能会很好,除非嵌套级别太高,然后您得到一个 RuntimeError:超过最大递归深度
。为了解决这个问题,您可以使用常规技术进行递归删除:保留自己的堆栈以检查(作为在您的控制下的列表)。即:
@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
; - ),明显的例外是递归调用被替换为而
循环和 .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
.
这篇关于假设我有一个python字典,很多巢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!