I wish to access the value of 'elevation'
ie 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"
}
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.