Wunderground API 获取每小时预测返回错误.- Python [英] Wunderground API to get hourly forecast returns error. - Python
问题描述
我正在尝试从 Wunderground API 获取每小时预报,但我的代码返回此错误.
I'm trying to get the hourly forecast from the Wunderground API but my code returns this error.
回溯(最近一次调用最后一次):文件weathergraph.py",第 10 行,在预测 = parsed_json['hourly_forecast']['FCTTIME']['temp']['english']类型错误:列表索引必须是整数,而不是 str
Traceback (most recent call last): File "weathergraph.py", line 10, in forecast = parsed_json['hourly_forecast']['FCTTIME']['temp']['english'] TypeError: list indices must be integers, not str
这是我的代码.
f=urllib2.urlopen('http://api.wunderground.com/api/mykey/hourly/q/NY/New_York_City.json')
f=urllib2.urlopen('http://api.wunderground.com/api/mykey/hourly/q/NY/New_York_City.json')
json_string = f.read()
json_string = f.read()
parsed_json = json.loads(json_string)
parsed_json = json.loads(json_string)
forecast = parsed_json['hourly_forecast']['FCTTIME']['temp']['english']
forecast = parsed_json['hourly_forecast']['FCTTIME']['temp']['english']
f.close()
parsed_json = http://pastie.org/3905346
parsed_json = http://pastie.org/3905346
推荐答案
1) hourly_forecast 的值是一个字典列表,而不是一个字典.列表中大约有 36 个.
1) The value of hourly_forecast is a list of dicts, not a dict. Looks like about 36 in the list.
2) temp 不是 FCTTIME 的一个元素.他们处于同一水平
2) temp is not an element of FCTTIME. They are at the same level
这不应产生错误:
forecast = parsed_json['hourly_forecast'][-1]['temp']['english']
看起来列表是按时间排序的,所以最后一个是最新的.检查FCTTIME的内容会告诉您是否与您上次阅读的内容有所不同.
It looks like the list is in order by time, so the last one is most recent. Checking the contents of FCTTIME will tell you whether it is different from the last time that you read it.
这篇关于Wunderground API 获取每小时预测返回错误.- Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!