循環(huán)遍歷所有嵌套的字典值?for k, v in d.iteritems():
if type(v) is dict:
for t, c in v.iteritems():
print "{0} : {1}".format(t, c)我試圖循環(huán)遍歷一個(gè)字典,并打印出值不是嵌套字典的所有鍵值對(duì)。如果這個(gè)值是一個(gè)字典,我想進(jìn)入它并打印出它的鍵值對(duì)…等等。有什么幫助嗎?編輯這個(gè)怎么樣?它仍然只印了一件東西。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'}}結(jié)果:xml : {u'config': {u'portstatus': {u'status': u'good'}, u'target': u'1'}, u'port': u'11'}
3 回答

ibeautiful
TA貢獻(xiàn)1993條經(jīng)驗(yàn) 獲得超6個(gè)贊
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貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超4個(gè)贊
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))
添加回答
舉報(bào)
0/150
提交
取消