Tyler
Tyler

Reputation: 11

keyerror while checking for values that exists in a dictionary

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'

Upvotes: 0

Views: 507

Answers (3)

RNovey
RNovey

Reputation: 58

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.

Upvotes: 0

Uncle Dino
Uncle Dino

Reputation: 864

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.

Upvotes: 1

john
john

Reputation: 1

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

Upvotes: 0

Related Questions