gpt4 book ai didi

python - 在 Python 中遍历 JSON 列表时出现问题?

转载 作者:太空狗 更新时间:2023-10-29 17:39:19 27 4
gpt4 key购买 nike

我有一个包含 JSON 数据的文件,如下所示:

{
"Results": [
{"Id": "001",
"Name": "Bob",
"Items": {
"Cars": "1",
"Books": "3",
"Phones": "1"}
},

{"Id": "002",
"Name": "Tom",
"Items": {
"Cars": "1",
"Books": "3",
"Phones": "1"}
},

{"Id": "003",
"Name": "Sally",
"Items": {
"Cars": "1",
"Books": "3",
"Phones": "1"}
}]
}

我不知道如何正确地遍历 JSON。我想遍历数据并为数据集中的每个成员获取一个带有 Cars 的名称。我怎样才能做到这一点?

import json

with open('data.json') as data_file:
data = json.load(data_file)

print data["Results"][0]["Name"] # Gives me a name for the first entry
print data["Results"][0]["Items"]["Cars"] # Gives me the number of cars for the first entry

我试过循环遍历它们:

for i in data["Results"]:
print data["Results"][i]["Name"]

但是收到一个错误:类型错误:列表索引必须是整数,而不是字典

最佳答案

你假设 i 是一个索引,但它是一个字典,使用:

for item in data["Results"]:
print item["Name"]

引自for Statements :

The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

关于python - 在 Python 中遍历 JSON 列表时出现问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34951448/

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