在Python中迭代嵌套的Dictionary和Sub Dictionary

时间:2016-12-21 18:33:56

标签: python python-3.x dictionary

JSON:

data = {"result":[{"name":"Teddy","list":{"0":"24","1":"43","2":"56"}},
           {"name":"Barney","list":{"0":"24","1":"43","2":"56"}]}

代码:

i = 0
j = 0
for p in data['result']:
    print('Name: ' + p['name'])
    for v in p['list']:
        i += 1
        print("{0} : {1}".format(i,v[j]))
        j += 1

我正在尝试访问每个值并打印出来,但不幸的是,没有任何成功,任何帮助都表示赞赏。

我见过:Loop through all nested dictionary values?

1 个答案:

答案 0 :(得分:3)

从您的尝试来看,您想要做的事情似乎如下:

data = {"result":[
    {"name":"Teddy","list":{"0":"24","1":"43","2":"56"}},
    {"name":"Barney","list":{"0":"24","1":"43","2":"56"}}]}

for p in data['result']:
    print('Name: ' + p['name'])
    for k, v in p['list'].items():
        print("{0} : {1}".format(k,v))

请注意,data不是JSON对象,而是Python字典。

<强>输出:

Name: Teddy
1 : 43
0 : 24
2 : 56
Name: Barney
1 : 43
0 : 24
2 : 56