[英]Getting values from JSON file
我试图从计数中获取值并添加它们以查找总和。 我写的代码是:
import json
data= '''
{
"note":" sample data ",
"comments":
[
{
"School":"UCLA",
"count":97
},
{
"School":"MIT",
"count":97
},
{
"School":"Rutgers",
"count":90
}
]
}'''
number=list()
a=0
b=0
info = json.loads (data)
print json.dumps(info, indent=4)
for i in info:
number= i["comments"][0]["count"]
for n in number:
a=float(n)
b+=a
print b
当我执行此操作时,我得到的输出是:
Traceback (most recent call last):
File "testty.py", line 28, in <module>
number= i["comments"][0]["count"]
TypeError: string indices must be integers
有人可以告诉我我做错了什么以及如何解决它。
谢谢
你应该循环遍历info["comments"]
这是一个列表。 您还可以使用sum
函数来累计值
b = sum(float(i["count"]) for i in info["comments"])
这个:
for i in info:
迭代dict,产生键,这是键。 直接访问info
。
这是python列表理解:
tt = sum([float(row['count']) for row in info['comments']])
print tt
或者这是“for”循环
tt = []
for row in info['comments']:
tt.append(float(row['count']))
b = sum(tt)
print b
列表理解通常更快......
你的代码:
data= '''
[{
"note":" sample data ",
"comments":
[
{
"School":"UCLA",
"count":97
},
{
"School":"MIT",
"count":97
},
{
"School":"Rutgers",
"count":90
}
]
}]'''
使用上面的数据作为数据,你的代码应该工作......你缺少打开'['和关闭']'...
顶级JSON对象不是数组,因此不应对其进行迭代。 数组在info["comments"]
,所以也是
for i in info["comments"]:
a = float(i["count"])
b += a
print b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.