相关疑难解决方法(0)

循环遍历所有嵌套字典值?

for k, v in d.iteritems():
    if type(v) is dict:
        for t, c in v.iteritems():
            print "{0} : {1}".format(t, c)
Run Code Online (Sandbox Code Playgroud)

我正在尝试遍历字典并打印出值不是嵌套字典的所有键值对.如果值是字典,我想进入它并打印出其键值对...等.有帮助吗?

编辑

这个怎么样?它仍然只打印一件事.

def printDict(d):
    for k, v in d.iteritems():
        if type(v) is dict:
            printDict(v)
        else:
            print "{0} : {1}".format(k, v)
Run Code Online (Sandbox Code Playgroud)

完整测试案例

字典:

{u'xml': {u'config': {u'portstatus': {u'status': u'good'}, u'target': u'1'},
      u'port': u'11'}}
Run Code Online (Sandbox Code Playgroud)

结果:

xml : {u'config': {u'portstatus': {u'status': u'good'}, u'target': u'1'}, u'port': u'11'}
Run Code Online (Sandbox Code Playgroud)

python dictionary

93
推荐指数
7
解决办法
18万
查看次数

标签 统计

dictionary ×1

python ×1