如何通过Weather Underground API获取JSON中的当日气温高低值?
解决Weather Underground API仅获取当日气温的问题
嘿,我来帮你搞定这个问题!你碰到的TypeError其实是把列表和字典的访问方式搞混了,咱们一步步理清楚:
首先,data['forecast']['simpleforecast']['forecastday']是一个列表,里面的每个元素才是包含period、high、low这些字段的字典。你之前写的['period':1]是字典的切片语法,放在列表上肯定会报错——列表只能用整数索引或者整数切片,比如[0]取第一个元素,[0:2]取前两个元素。
最简便的方法:直接取列表第一个元素
根据Weather Underground API的返回结构,forecastday列表的第一个元素正好就是当日的数据(对应period:1),所以完全不需要循环,直接通过索引获取就行:
import requests r = requests.get("http://api.wunderground.com/api/API/forecast/q/NV/Las_Vegas.json") data = r.json() # 直接获取当日数据(列表的第一个元素,索引从0开始) today = data['forecast']['simpleforecast']['forecastday'][0] print(f"{today['date']['weekday']}:") print(f"Conditions: {today['conditions']}") print(f"High: {today['high']['fahrenheit']}F, Low: {today['low']['fahrenheit']}F")
更稳妥的方法:筛选period=1的元素
如果担心未来API返回的列表顺序可能变化(虽然概率很低),可以遍历列表,专门找出period等于1的元素:
import requests r = requests.get("http://api.wunderground.com/api/API/forecast/q/NV/Las_Vegas.json") data = r.json() # 遍历列表,定位period为1的当日数据 today = None for day in data['forecast']['simpleforecast']['forecastday']: if day['period'] == 1: today = day break # 找到后立刻退出循环,不用继续遍历 if today: print(f"{today['date']['weekday']}:") print(f"Conditions: {today['conditions']}") print(f"High: {today['high']['fahrenheit']}F, Low: {today['low']['fahrenheit']}F") else: print("未找到当日数据")
为啥你之前的代码会报错?
再回头说下错误的根源:
- 你试图在
forecastday这个列表上直接用['period':1],但列表没有period这个键,只有它的元素(每个字典)才有; - 切片语法
['period':1]是字典的用法,列表的切片必须是整数,比如[0:1],但这也只是取第一个元素的切片,不是筛选period=1的元素。
这样修改后,就能精准拿到当日的最高温和最低温啦!
内容的提问来源于stack exchange,提问作者john smith
相关产品推荐
相关产品推荐

