相关疑难解决方法(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万
查看次数

在嵌套的Python字典中搜索密钥

我有一些像这样的Python词典:

A = {id: {idnumber: condition},.... 
Run Code Online (Sandbox Code Playgroud)

例如

A = {1: {11 : 567.54}, 2: {14 : 123.13}, .....
Run Code Online (Sandbox Code Playgroud)

我需要搜索字典中是否有任何字典idnumber == 11并使用condition.但如果在整个字典中没有idnumber == 11,我需要继续下一个字典.

这是我的尝试:

for id, idnumber in A.iteritems():
    if 11 in idnumber.keys(): 
       calculate = ......
    else:
       break
Run Code Online (Sandbox Code Playgroud)

python recursion dictionary nested

5
推荐指数
2
解决办法
8655
查看次数

标签 统计

dictionary ×2

python ×2

nested ×1

recursion ×1