Like other answers have pointed out, the accepted answer to this question seems to ignore the data structure misunderstanding of the original poster.
The main issue seems to be that the original solution treats the JSON purely as a dictionary, when in fact it is a...
dictionary within a list, within a dictionary, within a dictionary
Thus,
['data']
is required to access the top-level key:value pair of the dictionary,
['current_conditions']
accesses the next level of dictionary,
then [0]
must be used to access the first element of the list (which has only 1 element).
Only then can ['temp_C']
be used to access the actual value for that key and retrieve the data.
x={
"data": {
"current_condition":
[{
"cloudcover": "0",
"humidity": "54",
"observation_time": "08:49 AM",
"precipMM": "0.0",
"pressure": "1025",
"temp_C": "10",
"temp_F": "50",
"visibility": "10",
"weatherCode": "113",
"weatherDesc":
[{
"value": "Sunny"
}],
"weatherIconUrl":
[{
"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png"
}],
"winddir16Point": "E",
"winddirDegree": "100",
"windspeedKmph": "22",
"windspeedMiles": "14"
},
{
"cloudcover": "0",
"humidity": "54",
"observation_time": "08:49 AM",
"precipMM": "0.0",
"pressure": "1025",
"temp_C": "5",
"temp_F": "50",
"visibility": "10",
"weatherCode": "113",
"weatherDesc":
[{
"value": "Sunny"
}],
"weatherIconUrl":
[{
"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png"
}],
"winddir16Point": "E",
"winddirDegree": "100",
"windspeedKmph": "22",
"windspeedMiles": "14"
} ]
}
}
print(x['data']['current_condition'][0]['weatherDesc'][0]['value'])
# results in 'Sunny'
In answer to another question in comments,
"Is there a way to do this without knowing the index, assuming there
were more current condition entries?"
Assuming numerous current_condition
entries it is unlikely that you would just want one value, or if you do then you'll likely have another piece of information to locate that specific value (i.e. location or something).
Assuming you data set is named x
, i.e. x = {"data": ...}
.
If you want all of the current_condition
entries you can loop through the list (of current_conditions
) using:
y = []
for index in range(0,len(x['data']['current_condition']))
y.append(x['data']['current_condition'][index]['temp_C'])