Search code examples
pythonkeyerror

Keyerror while trying to pull Zipcode from Google Reverse Geocoding


Am new to Python and am trying to parse out just the zip code from a list (using Googlemaps package) and am running into a KeyError.

import googlemaps
gmaps = googlemaps.Client('my_api_key')
reverse_geocode_result = gmaps.reverse_geocode((lat,lng))
address = reverse_geocode_result
x=address[0][0]
print(len(x))

Error message Traceback (most recent call last): File "Gmaps2.py", line 10, in x=address[0][0] KeyError: 0


Solution

  • address[0] should be a dictionary object - you can access its contents with keys, rather than using a numerical index (which is something you would do for a list).

    >>> address[0].keys()
    [u'geometry', u'address_components', u'place_id', u'formatted_address', u'types']
    
    >>> address[0]['address_components'][8]['long_name']
    u'90005'