我有一个像这样的嵌套字典{“ 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:']
答案 0 :(得分:0)
此函数将打印带有缩进的嵌套字典的键:
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
(这或多或少是here中xml的缩进功能)。
答案 1 :(得分:0)
new_d={"step1": {}, "step2": {"step3": {"step4": {}},'step7':{}}}
def fn(d, counter):
for k, v in d.items():
yield '\t' * counter + k
if isinstance(v, dict):
yield from fn(v, counter + 1)
out = []
for p in fn(new_d, 0):
out += [p]
print(out)
打印:
['step1', 'step2', '\tstep3', '\t\tstep4', '\tstep7']
答案 2 :(得分:0)
您已经说过,简单的递归就可以了:
def put_tabs(d, level=0):
rv = []
prefix = '\t' * level
for key in d:
rv.append(prefix+key)
if type(d[key]) == dict and len(d[key]) > 0:
rv.extend(put_tabs(d[key], level=level+1))
return rv
d = {"step1": {}, "step2": {"step3": {"step4": {}}, "step7": {}}}
print(put_tabs(d))
# ['step1', 'step2', '\tstep3', '\t\tstep4', '\tstep7']