gpt4 book ai didi

python - 在 Python 中遍历嵌套字典和子字典

转载 作者:行者123 更新时间:2023-12-03 20:11:19 25 4
gpt4 key购买 nike

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?

最佳答案

从您的尝试看来,您想要做的是以下内容:

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

关于python - 在 Python 中遍历嵌套字典和子字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41269633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com