在使用 Python 的过程中,有时需要从数据中读取字典格式的文件,并且字典的值可能仍然是字典,这时直接通过 print
打印的方式获取数据结构是很不方便的,这个函数通过递归的方式将字典树的键以缩进格式打印出来,可以清晰地查看数据结构。支持列表和字典的递归嵌套。
def show_recursive(obj, depth=0, maxdepth=10):
if depth >= maxdepth:
return
if isinstance(obj, dict):
for key, val in obj.items():
print('\t' * depth, '-', key)
show_recursive(val, depth=depth+1, maxdepth=maxdepth)
elif isinstance(obj, list):
print('\t' * depth, '<li>')
for elem in obj:
show_recursive(elem, depth=depth, maxdepth=maxdepth)