I keep getting a keyerror
in python.
I am using requests
and getting back a json
with 3 values. I am trying to extract only the elevation.
r = requests.get(api_url +str(lat) +"," +str(longi) )
resp = json.loads(r.text)
print(resp)
print(resp['elevation'])
this is the response for resp
:
{'results': [{'latitude': 30.654543, 'longitude': 35.235351, 'elevation': -80}]}
this is the error:
KeyError: 'elevation'
It is responding with a list (holding one dictionary) as the value. So you would access with resp["results"][0]["elevation"] because "elevation" is not in results, it is in results[0] (zero index of the list results) and you can tell this by the "[{ }]" denoting a list holding a dictionary.