我有一个像这样的嵌套字典 {"step1": {}, "step2": {"step3": {"step4": {}},'step7':{}}},现在我需要递归迭代嵌套字典并创建嵌套字典的键列表,并在其前面添加制表符。
new_d={"step1": {}, "step2": {"step3": {"step4": {}},'step7':{}}}
other_list=[]
child=False
tabb='\t'
def put_tabs(d):
global tabb,child
for k, v in d.iteritems():
if v:
if child:
other_list.append("{0}{1}".format(tabb,k))
tabb+='\t'
else:
other_list.append("{0}".format(k))
child=True
put_tabs(v)
else:
if child:
other_list.append("{0}{1}".format(tabb,k))
else:
other_list.append("{0}:".format(k))
child=False
put_tabs(new_d)
print other_list
# Expected output ['step2', '\tstep7', '\tstep3', '\t\tstep4', 'step1:']
# current ouput ['step2', '\tstep7', 'step3', '\t\step4', 'step1:']
这是一个函数,它将打印带有缩进的嵌套字典的键:
def indent_dict(d, indent=0):
for key, value in d.iteritems(): # python 2
# for key, value in d.items(): # python 3
print("\t" * indent + str(key))
if isinstance(value, dict):
indent_dict(value, indent + 1)
else:
print("\t" * (indent + 1) + str(value))
供您输入
new_d = {"step1": {}, "step2": {"step3": {"step4": {}}, "step7": {}}}
indent_dict(new_d)
它输出:
step1
step2
step3
step4
step7
(这或多或少是来自此处的xml 的缩进功能)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句