如何访问字典键中列表项中的元素?

时间:2019-05-30 11:54:30

标签: python json python-3.x

我目前有一个JSON文件,可以输出各种天气数据。我可以在一定程度上优化我想要的信息,但是需要进一步优化,但是无法。

我尝试根据位置[1]选择它,并且我还尝试根据键(例如)访问数据。 ['weather'],但在Python引发错误之前,我只能进行很多改进。

{'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}

上面的代码是我必须使用的JSON文件,我想优化和提取例如“ weather”中的“ main”值,因此我想提取字符串“ Clouds”,但是我已经尝试过就像dict ['weather] ['main']一样,但是它只会引发错误。

正在寻找一些建议:D

1 个答案:

答案 0 :(得分:5)

weather的值是一个列表,因此您需要dict['weather'][0]['main']

此外,我建议不要调用特定的字典dict,因为它会隐藏内置的dict函数。

相关问题