Rom*_*man 4 python recursion json dictionary
我有一个非常深的json对象.换句话说,我有一个字典,包含多次包含词典的词典等等.因此,可以将它想象成一棵巨大的树,其中一些节点离根节点很远.
现在我想切割这棵树,这样我就只有从根部分开不超过N步的节点.有一个简单的方法吗?
例如,如果我有:
{'a':{'d':{'e':'f', 'l':'m'}}, 'b':'c', 'w':{'x':{'z':'y'}}}
Run Code Online (Sandbox Code Playgroud)
我想只保留距离根2步的节点,我应该得到:
{'a':{'d':'o1'}, 'b':'c', 'w':{'x':'o2'}}
Run Code Online (Sandbox Code Playgroud)
所以,我只用单个值替换远端词典.
鉴于您的数据非常深,您可能会在递归时遇到堆栈限制.这是一种迭代方法,您可以清理和润色一下:
import collections
def cut(dict_, maxdepth, replaced_with=None):
"""Cuts the dictionary at the specified depth.
If maxdepth is n, then only n levels of keys are kept.
"""
queue = collections.deque([(dict_, 0)])
# invariant: every entry in the queue is a dictionary
while queue:
parent, depth = queue.popleft()
for key, child in parent.items():
if isinstance(child, dict):
if depth == maxdepth - 1:
parent[key] = replaced_with
else:
queue.append((child, depth+1))
Run Code Online (Sandbox Code Playgroud)