遍历Python中的嵌套词典和子词典 [英] Iterate through a nested Dictionary and Sub Dictionary in Python

查看:101
本文介绍了遍历Python中的嵌套词典和子词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我正在尝试访问每个值并打印出来,但是很遗憾,如果没有成功,我们将不胜感激.

I am trying to access each value and print them out, but unfortunately, without any success, any help is appreciated.

我已经看到:遍历所有嵌套的字典值吗?

I have seen: Loop through all nested dictionary values?

推荐答案

从您的尝试看来,您想要执行的操作如下:

From your attempt, seems that what you want to do is the following:

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字典.

Note that data is not a JSON object but a Python dictionary.

输出:

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

这篇关于遍历Python中的嵌套词典和子词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆