Reputation: 45
I wish to access the value of 'elevation'
i.e. 1608.637939453125
and store it into the variable 'g'
. Below is the code
import requests, json
r = requests.get(api link)
r= json.loads(r.text)
g=r['results']['elevation']
the above code returns this error
TypeError: list indices must be integers or slices, not str
Here's the dictionary data
{
"results" : [
{
"elevation" : 1608.637939453125,
"location" : {
"lat" : 39.7391536,
"lng" : -104.9847034
},
"resolution" : 4.771975994110107
}
],
"status" : "OK"
}
Upvotes: 0
Views: 26
Reputation: 51175
In this case, results
is a list of dictionaries, not another dictionary. So you have to access the value of elevation
like this:
g = x['results'][0]['elevation']
If results had more entries in the list, which is common, you can loop through them like this:
for result in x['results']:
print(result)
Upvotes: 1