问题描述
我正在尝试按照网站上提到的方法访问气象站数据:https://towardsdatascience.com/getting-weather-data-in-3-easy-steps-8dc10cc5c859我正在为此使用python。我仍在学习python,我不知道为什么它显示错误。我使用的代码行是:
r = requests.get('https://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=GHCND&datatypeid=\
TAVG&limit=1000&stationid=GHCND:USC00297461&startdate=2020-01-01&enddate=2020-10-22',headers={'token':Token})
d = r.json()
avg_temps = [item for item in d['results'] if item['datatype']=='TAVG']
错误是:
KeyError Traceback (most recent call last)
<ipython-input-85-c1a56919f6ab> in <module>()
4 d = r.json()
5 #get the item (average temperature) from the response
----> 6 avg_temps = [item for item in d['results'] if item['datatype']=='TAVG']
KeyError: 'results'
解决方法
你收到一个错误,因为你应该有这个
avg_temps = [item for item in d['results'] if item['datatype']=='TAVG']
而不是这个:
avg_temps = [item for item in d['results'] if d['datatype']=='TAVG']
差异是item['datatype']
反而
d['datatype']