循环遍历所有嵌套的字典值? [英] Loop through all nested dictionary values?
问题描述
如果type(v)是dict:
for t,c in v.iteritems()中:
print{0}:{1}。format(t,c)
我试图循环通过一个字典,并打印所有键值对,其中值不是一个嵌套的字典。如果该值是字典,我想进入它并打印出它的键值对...等等。任何帮助?
编辑
这怎么样?它仍然只打印一件事。
def printDict(dict):
for k,v in dict.iteritems )
如果type(v)是dict:
printDict(v)
else:
print{0}:{1}。format(k,v)
全部测试用例
词典: p>
{u'xml':{u'config':{u'portstatus':{u'status':u'good' },u'target':u'1'},
u'port':u'11'}}
结果:
xml:{u'config':{u'portstatus':{u'状态':你好'},u'target':u'1'},u'port':u'11'}
正如Niklas所说,你需要递归,即你想定义一个函数来打印你的dict,如果该值是一个dict,你想要使用这个新的命令来调用你的打印功能。
这样的东西:
DEF myprint(d):
for k,v in d.iteritems():
if isinstance(v,dict):
myprint(v)
else:
打印{0}:{1}。格式(k,v)
或为Python 3向前:
def myprint(d):
for k,v in d.items():
if isinstance(v,dict):
myprint(v)
else:
print({0}:{1}。format(k,v))
for k, v in dict.iteritems():
if type(v) is dict:
for t, c in v.iteritems():
print "{0} : {1}".format(t, c)
I'm trying to loop through a dictionary and print out all key value pairs where the value is not a nested dictionary. If the value is a dictionary I want to go into it and print out its key value pairs...etc. Any help?
EDIT
How about this? It still only prints one thing.
def printDict(dict):
for k, v in dict.iteritems():
if type(v) is dict:
printDict(v)
else:
print "{0} : {1}".format(k, v)
Full Test Case
Dictionary:
{u'xml': {u'config': {u'portstatus': {u'status': u'good'}, u'target': u'1'},
u'port': u'11'}}
Result:
xml : {u'config': {u'portstatus': {u'status': u'good'}, u'target': u'1'}, u'port': u'11'}
As said by Niklas, you need recursion, i.e. you want to define a function to print your dict, and if the value is a dict, you want to call your print function using this new dict.
Something like :
def myprint(d):
for k, v in d.iteritems():
if isinstance(v, dict):
myprint(v)
else:
print "{0} : {1}".format(k, v)
Or for Python 3 onwards :
def myprint(d):
for k, v in d.items():
if isinstance(v, dict):
myprint(v)
else:
print("{0} : {1}".format(k, v))
这篇关于循环遍历所有嵌套的字典值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!