我有很多嵌套的字典,我试图找到嵌套在某个地方的某个键.
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.
更多推荐
在深度嵌套的字典中查找键
发布评论