在Python中迭代JSON列表的问题?

Baj*_*jan 13 python arrays json for-loop

我有一个包含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"}
            }]
}
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何正确循环JSON.我想遍历数据并为数据集中的每个成员获取一个带有汽车的名称.我怎么能做到这一点?

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
Run Code Online (Sandbox Code Playgroud)

我试过通过它们循环:

for i in data["Results"]:
print data["Results"][i]["Name"]    
Run Code Online (Sandbox Code Playgroud)

但是收到一个错误: TypeError:list indices必须是整数,而不是dict

ale*_*cxe 18

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

for item in data["Results"]:
    print item["Name"]    
Run Code Online (Sandbox Code Playgroud)

引用来自声明:

Python中的for语句与您在C或Pascal中使用的语句略有不同.而不是总是迭代数字的算术级数(如在Pascal中),或者让用户能够定义迭代步骤和暂停条件(如C),Python的for语句迭代任何序列的项目(列表或字符串),按照它们出现在序列中的顺序.

  • @Bajan肯定,假设你的意思是`Items`字典:`for key,value in item ["Items"].iteritems():`.请参阅相关主题:https://docs.python.org/2/tutorial/datastructures.html#dictionaries,http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops-在-蟒蛇. (2认同)

geo*_*ncl 6

你正在遍历字典而不是索引,所以你应该使用.

for item in data["Results"]:
    print item["Name"]    
Run Code Online (Sandbox Code Playgroud)

要么

for i in range(len(data["Results"])):
    print data["Results"][i]["Name"]
Run Code Online (Sandbox Code Playgroud)


Tad*_*sen 5

混淆在于如何在迭代中使用字典和列表。字典将迭代它的键(您将其用作索引以获取相应的值)

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)
Run Code Online (Sandbox Code Playgroud)

但是迭代列表的默认行为会给你元素而不是索引:

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)
Run Code Online (Sandbox Code Playgroud)

如果您想将您的程序概括为以相同的方式处理这两种类型,您可以使用以下函数之一:

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))
Run Code Online (Sandbox Code Playgroud)

这样,例如,如果您稍后更改 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"])
Run Code Online (Sandbox Code Playgroud)