假设我有一个python字典,很多巢 [英] Suppose I have a python dictionary , many nests

查看:91
本文介绍了假设我有一个python字典,很多巢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有很多嵌套字典,我试图找到一个特定的键。

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屋!

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