我有一个包含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。我想遍历数据并为数据集中的每个成员获取一个带有汽车的名称。我怎么能做到这一点?
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"]
但收到错误: TypeError:列表索引必须是整数,而不是dict
答案 0 :(得分:16)
您假设#include<iostream>
using namespace std;
int main ()
{
int i,j;
double ave,scores,total=0.0;
for(j=1;j<=5;j++)
{
cout<<"Marks for Student"<<j<<":"<<endl;
for(i=1;i<=3;i++)
{
cout<<" subject"<<i<<":";
cin>>scores;
total+=scores;
}
ave=total/3;
// Changes here
cout<<"average:" << ave << endl; // print it here
ave=0; // zero it out
cout<<endl;
}
return 0;
}
是一个索引,但它是一个字典,请使用:
i
的引用
Python中的for语句与您在C或Pascal中使用的语句略有不同。而不是总是迭代数字的算术级数(如在Pascal中),或者让用户能够定义迭代步骤和暂停条件(如C), Python的for语句迭代任何序列的项目(列表或字符串),按顺序出现在序列中。
答案 1 :(得分:6)
你正在迭代字典而不是索引,所以你应该使用。
for item in data["Results"]:
print item["Name"]
或
for i in range(len(data["Results"])):
print data["Results"][i]["Name"]
答案 2 :(得分: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"])
答案 3 :(得分:1)
for json_data in data['Results']:
for attribute, value in json_data.iteritems():
print attribute, value # example usage