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

2024-05-15 23:42:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含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"]    

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


Tags: the数据nameidjsonfordataitems
3条回答

混淆的是词典和列表在迭代中的使用方式。 字典将遍历它的键(用作索引以获取相应的值)

x = {"a":3,  "b":4,  "c":5}
for key in x:   #same thing as using x.keys()
   print(key,x[key]) 

for value in x.values():
    print(value)      #this is better if the keys are irrelevant     

for key,value in x.items(): #this gives you both
    print(key,value)

但是遍历列表的默认行为将为您提供元素而不是索引:

y = [1,2,3,4]
for i in range(len(y)):  #iterate over the indices
    print(i,y[i])

for item in y:
    print(item)  #doesn't keep track of indices

for i,item in enumerate(y): #this gives you both
    print(i,item)

如果要将程序泛化为处理这两种类型,可以使用以下函数之一:

def indices(obj):
    if isinstance(obj,dict):
        return obj.keys()
    elif isinstance(obj,list):
        return range(len(obj))
    else:
        raise TypeError("expected dict or list, got %r"%type(obj))

def values(obj):
    if isinstance(obj,dict):
        return obj.values()
    elif isinstance(obj,list):
        return obj
    else:
        raise TypeError("expected dict or list, got %r"%type(obj))

def enum(obj):
    if isinstance(obj,dict):
        return obj.items()
    elif isinstance(obj,list):
        return enumerate(obj)
    else:
        raise TypeError("expected dict or list, got %r"%type(obj))

例如,如果您后来更改了json以使用id作为键将结果存储在dict中,那么程序仍将以相同的方式遍历它:

#data = <LOAD JSON>
for item in values(data["Results"]):
    print(item["name"])

#or
for i in indices(data["Results"]):
    print(data["Results"][i]["name"])

您正在遍历字典而不是索引,因此应该使用。

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

或者

for i in range(len(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.

相关问题 更多 >