You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何访问字典键下列表元素的值?Python天气JSON数据提取求助

解决JSON提取weather.main报错的问题

嘿,这问题我熟!你之所以用dict['weather']['main']会报错,核心原因是**weather对应的是一个列表(list),而不是字典(dict)**。你看你的JSON数据里,weather是用方括号[]包裹的,里面才是包含main键的字典对象。

正确提取方式

先定位到weather列表里的具体字典元素,再通过键名提取main值。因为你的数据里weather列表只有一个元素,用索引[0]就能拿到它:

# 先把你的JSON数据赋值给变量
weather_data = {'coord': {'lon': -1.98, 'lat': 50.72}, 'weather': [{'id': 803, 'main': 'Clouds', 'description': 'broken clouds', 'icon': '04d'}], 'base': 'stations', 'main': {'temp': 293.6, 'pressure': 1022, 'humidity': 64, 'temp_min': 292.15, 'temp_max': 294.82}, 'visibility': 10000, 'wind': {'speed': 5.1, 'deg': 230}, 'clouds': {'all': 75}, 'dt': 1559214671, 'sys': {'type': 1, 'id': 1401, 'message': 0.0072, 'country': 'GB', 'sunrise': 1559188945, 'sunset': 1559246925}, 'timezone': 3600, 'id': 2640101, 'name': 'Poole', 'cod': 200}

# 提取weather下的main值
cloud_type = weather_data['weather'][0]['main']
print(cloud_type)  # 输出: Clouds

拓展:如果weather列表有多个元素怎么办?

要是API返回的weather里有多个天气条目,你可以用循环遍历所有元素,逐个提取main值:

for weather_item in weather_data['weather']:
    print(weather_item['main'])

这样就能把所有天气类型都取出来啦!

内容的提问来源于stack exchange,提问作者Yarry T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:46:51