循环遍历所有嵌套的字典值?for k, v in d.iteritems():
if type(v) is dict:
for t, c in v.iteritems():
print "{0} : {1}".format(t, c)我试图循环遍历一个字典,并打印出值不是嵌套字典的所有键值对。如果这个值是一个字典,我想进入它并打印出它的键值对…等等。有什么帮助吗?编辑这个怎么样?它仍然只印了一件东西。def printDict(d):
for k, v in d.iteritems():
if type(v) is dict:
printDict(v)
else:
print "{0} : {1}".format(k, v)全测试用例字典:{u'xml': {u'config': {u'portstatus': {u'status': u'good'}, u'target': u'1'},
u'port': u'11'}}结果:xml : {u'config': {u'portstatus': {u'status': u'good'}, u'target': u'1'}, u'port': u'11'}
3 回答
ibeautiful
TA贡献1993条经验 获得超5个赞
def myprint(d): for k, v in d.iteritems(): if isinstance(v, dict): myprint(v) else: print "{0} : {1}".format(k, v)
def myprint(d): for k, v in d.items(): if isinstance(v, dict): myprint(v) else: print("{0} : {1}".format(k, v))
明月笑刀无情
TA贡献1828条经验 获得超4个赞
def myprint(d): stack = d.items() while stack: k, v = stack.pop() if isinstance(v, dict): stack.extend(v.iteritems()) else: print("%s: %s" % (k, v))
添加回答
举报
0/150
提交
取消