Yarry T
Yarry T

Reputation: 169

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. 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 e.g [1] and I have also tried to access the data based on keys e.g. ['weather'] but I can only refine it so much before Python throws an error.

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

Looking for some advice :D

Upvotes: 2

Views: 69

Answers (1)

user200783
user200783

Reputation: 14348

The value for weather is a list, so you'd need dict['weather'][0]['main'].

Also, I recommend not calling a particular dictionary dict, because it hides the built-in dict function.

Upvotes: 5

Related Questions