簡體   English   中英

如何從python中的JSON文件中選擇數據?

[英]how to select data from a JSON file in python?

我有一個像這樣的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文件包含許多具有上述結構的課程。 我該怎么做:

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發現這一點。

如果這是一個多個課程的列表,您需要按學生計算,請設置一個鍵入學生的詞典,其中包含整數。 使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM