[英]All keys with their depth of nested dictionary on Python
样本输入:
a = {
"key1": 1,
"key2": {
"key3": 1,
"key4": {
"key5": 4
}
}
}
示例输出:
key1 1
key2 1
key3 2
key4 2
key5 3
如何遍历此嵌套字典的每个元素并打印每个单独元素的深度?
使用递归:
def print_depth(d, start=0):
for key, value in d.items():
print(key, start + 1)
if isinstance(value, dict):
print_depth(value, start=start+1)
a = {
"key1": 1,
"key2": {
"key3": 1,
"key4": {
"key5": 4
}
}
}
print_depth(a)
输出
key1 1
key2 1
key3 2
key4 2
key5 3
使用堆栈避免超过递归限制(请参阅sys.getrecursionlimit ):
def print_depth(d):
stack = [(d, list(d.keys()))]
while stack:
cur, keys = stack.pop()
while keys:
k, keys = keys[0], keys[1:]
print(k, len(stack) + 1)
v = cur[k]
if isinstance(v, dict):
stack.append((cur, keys))
stack.append((v, list(v.keys())))
break
输出
key1 1
key2 1
key3 2
key4 2
key5 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.