gpt4 book ai didi

python - 如何从python中的JSON文件中选择数据?

转载 作者:太空宇宙 更新时间:2023-11-03 15:18:10 26 4
gpt4 key购买 nike

我有一个这样的 JSON 文件:

[
{
"course": "CMPT 102 D1",
"instructor": "hamarneh",
"students": [
"axc5",
"csf10",
"ctu1",
"nmw15",
"nsm12",
"ppy1",
"qtg13",
"tim1",
"tkd10",
"vhm8",
"vsv1",
"wps1",
"xup12",
"yqt6"
],
"title": "Scientific Cmpt.Prgm"
}]

这是我在 python 中的代码:

import json
json_data=open('jsonfile')
data=json.load(json_data)
print(data['students'])

但它显示错误:

   print(data['students'])
TypeError: list indices must be integers, not str

请帮忙!

还有一个问题:假设 JSON 文件包含许多具有上述结构的类(class)。我该怎么做:

Select students, count(course) as course_number from tblstudent
group by students

最佳答案

您的 JSON 包含一个列表,其中有一个字典;字典周围有两个方括号,[]

选择第一个元素:

print(data[0]['students'])

快速演示:

>>> print(data)
[{'instructor': 'hamarneh', 'course': 'CMPT 102 D1', 'title': 'Scientific Cmpt.Prgm', 'students': ['axc5', 'csf10', 'ctu1', 'nmw15', 'nsm12', 'ppy1', 'qtg13', 'tim1', 'tkd10', 'vhm8', 'vsv1', 'wps1', 'xup12', 'yqt6']}]
>>> print(data[0]['students'])
['axc5', 'csf10', 'ctu1', 'nmw15', 'nsm12', 'ppy1', 'qtg13', 'tim1', 'tkd10', 'vhm8', 'vsv1', 'wps1', 'xup12', 'yqt6']

请注意,您可以通过快速打印 data 自己发现这一点。

如果这是一个包含多个类(class)的列表,并且您需要对每个学生进行计数,请设置一个以学生为关键字的字典,其中包含整数。使用collections.defaultdict()使这更容易一些:

from collections import defaultdict

courses_per_student = defaultdict(int)

for course in data:
for student in course['students']:
courses_per_student[student] += 1

关于python - 如何从python中的JSON文件中选择数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19153009/

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