0

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'
2
  • 8
    Did you mean: print(resp['results'][0]['elevation'])? Commented Jul 30, 2022 at 10:59
  • 1
    Just want to explain the above comment. resp is, to say so, a dictionary with included list with included dictionary. resp["results"] returns you the list; resp["results"][0] returns you the first element of this list and it is the dictionary, and inside this dictionary there is the key elevation. Commented Jul 30, 2022 at 11:07

3 Answers 3

1

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 dicts).

  • resp['results'] would be [{'latitude': 30.654543, 'longitude': 35.235351, 'elevation': -80}] - the said array
  • resp['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.

Sign up to request clarification or add additional context in comments.

1 Comment

Be sure to always accept the answer if it solved your problem so others can find it too (and that also gives points to the answerer)
0

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.

Comments

0

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']

3 Comments

it's a list not an array
it is a list indeed
thx for the help, I now understand the error and got it to work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.