尝试从darksky API获取值列表时出错

时间:2017-04-18 20:10:05

标签: python python-3.x error-handling

我正在努力实现的目标:我正在尝试从darksky API获取最近7天的最高温度,最低温度和时间列表。当我尝试打印变量时,我一直得到这个(TypeError:'float'对象不可订阅)。最终结果是使用pandas将这些数据导入Dataframe,代码显然没有完成。

同样,答案可能很明显(newb here)。谢谢大家的帮助!

import pandas as pd 
import requests
import json 

key = '(my dark sky api key)'
url = 'https://api.darksky.net/forecast/%s/43.0481221,-76.147424' % (key)
response = requests.get(url)
weather_data = response.json()
time = weather_data['currently']['apparentTemperature']['daily']['data'][0:8]['time']
temperature_min = weather_data['currently']['apparentTemperature']['daily']['data'][0:8]['apparentTemperatureMin']
temperature_max = weather_data['currently']['apparentTemperature']['daily']['data'][0:8]['apparentTemperatureMax']

print(temperature_min)

TypeError: 'float' object is not subscriptable

1 个答案:

答案 0 :(得分:1)

显然问题在于你试图用来检索所需数据的数据结构和索引。

weather_data['currently']会给你字典对象:

{'apparentTemperature': 57.44,
 'cloudCover': 0.29,
 'dewPoint': 33.07,
 'humidity': 0.4,
 'icon': 'partly-cloudy-day',
 'nearestStormBearing': 242,
 'nearestStormDistance': 436,
 'ozone': 358.37,
 'precipIntensity': 0,
 'precipProbability': 0,
 'pressure': 1028.68,
 'summary': 'Partly Cloudy',
 'temperature': 57.44,
 'time': 1492546503,
 'visibility': 10,
 'windBearing': 4,
 'windSpeed': 2.16}

weather_data['currently']['apparentTemperature']提供float号码57.44。当您进一步尝试下标时,会引发错误,因为浮点数不可订阅。我建议调查更多weather_data数据结构,并选择正确的索引,这将提供您需要的数据。

试试这个:

time = [weather_data['daily']['data'][k]['time'] for k in range(0,8)]
temperature_min = [weather_data['daily']['data'][k]['apparentTemperatureMin'] for k in range(0,8)]
temperature_max = [weather_data['daily']['data'][k]['apparentTemperatureMax'] for k in range(0,8)]

此处列表推导用于检索数据8天。如果您希望收到某些特定日期,请使用特定日期list(例如[2,5,6])而不是range(0,8)