简体   繁体   English

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

[英]How do I access an element in a list item within a key of a dict?

I currently have a JSON file which outputs a wide range of weather data. 我目前有一个JSON文件,可输出各种天气数据。 I can refine the information I want to a certain degree but need to refine it one step further but am unable to. 我可以在一定程度上优化我想要的信息,但是需要进一步优化,但是无法。

I have tried selecting it based on location eg [1] and I have also tried to access the data based on keys eg ['weather'] but I can only refine it so much before Python throws an error. 我曾尝试根据位置(例如[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}

The above code is the JSON file that I have to work with, I want to refine and extract for example the 'main' value in 'weather' so I would like to extract the string 'Clouds' but I have tried things like dict['weather]['main'] but it simply throws up an error. 上面的代码是我必须使用的JSON文件,我想优化和提取例如“ weather”中的“ main”值,因此我想提取字符串“ Clouds”,但是我尝试了类似dict [ 'weather] ['main'],但它只会引发错误。

Looking for some advice :D 寻找一些建议:D

The value for weather is a list, so you'd need dict['weather'][0]['main'] . weather的值是一个列表,因此您需要dict['weather'][0]['main']

Also, I recommend not calling a particular dictionary dict , because it hides the built-in dict function. 另外,我建议不要调用特定的字典dict ,因为它会隐藏内置的dict函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM