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'
CodePudding user response:
If you format the JSON (resp
) a bit to be easier to undestand, you get something like this:
{
"results":[
{
"latitude":30.654543,
"longitude":35.235351,
"elevation":-80
}
]
}
(I used this tool)
You can see that the "toplevel" is an object (loaded as a python dict
) with a single key: "results"
, containing an array of objects (loaded as a python list
of dict
s).
resp['results']
would be[{'latitude': 30.654543, 'longitude': 35.235351, 'elevation': -80}]
- the said arrayresp['results'][0]
would be the 1st element of that array:{'latitude': 30.654543, 'longitude': 35.235351, 'elevation': -80}
resp['results'][0]['elevation']
would be-80
I suggest using a for
loop to iterate trough the elements of resp['results']
to process all resoults.
CodePudding user response:
The response is a dictionary whose 'results' key holds a list of dictionaries. In your case this list holds only one entry. So, you must traverse the entire path to get the value you want. Try: resp['results'][0]['elevation']
CodePudding user response:
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.