KMB
KMB

Reputation: 79

List of dictionaries - Function with list index is out of range

I am trying to loop through a variable of nested dictionaries (a JSON Google Maps output). The code below worked on a smaller output, but now it is returning an error.

The var geocode_result has a length of 28376.

lat_long_list = []
def geocode_results_process(x):         
    for i in range(len(x)):
        list_component = x[i][0]['geometry']['location']
        for val in list_component:
            latitude = list_component['lat']
        for val in list_component:
            longitude = list_component['lng']
        latlong = str(latitude) + ',' + str(longitude)
        lat_long_list.append(latlong)

geocode_results_process(geocode_result)

The expected result is a string list of the latitude and longitude appended to the lat_long_list.

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-167-18aa2be2eddd> in <module>
     13         lat_long_list.append(latlong)
     14 
---> 15 geocode_results_process(geocode_result)

<ipython-input-167-18aa2be2eddd> in geocode_results_process(x)
      5 def geocode_results_process(x):
      6     for i in range(len(x)):
----> 7         list_component = x[i][0]['geometry']['location']
      8         for val in list_component:
      9             latitude = list_component['lat']

IndexError: list index out of range

Sample of geocode_result:

geocode_result[1]

[{'address_components': [{'long_name': '620',
    'short_name': '620',
    'types': ['street_number']},
   {'long_name': 'South Broadway',
    'short_name': 'S Broadway',
    'types': ['route']},
   {'long_name': 'Downtown Los Angeles',
    'short_name': 'Downtown Los Angeles',
    'types': ['neighborhood', 'political']},
   {'long_name': 'Los Angeles',
    'short_name': 'Los Angeles',
    'types': ['locality', 'political']},
   {'long_name': 'Los Angeles County',
    'short_name': 'Los Angeles County',
    'types': ['administrative_area_level_2', 'political']},
   {'long_name': 'California',
    'short_name': 'CA',
    'types': ['administrative_area_level_1', 'political']},
   {'long_name': 'United States',
    'short_name': 'US',
    'types': ['country', 'political']},
   {'long_name': '90014', 'short_name': '90014', 'types': ['postal_code']},
   {'long_name': '1807',
    'short_name': '1807',
    'types': ['postal_code_suffix']}],
  'formatted_address': '620 S Broadway, Los Angeles, CA 90014, USA',
  'geometry': {'location': {'lat': 34.0459956, 'lng': -118.2523297},
   'location_type': 'ROOFTOP',
   'viewport': {'northeast': {'lat': 34.04734458029149,
     'lng': -118.2509807197085},
    'southwest': {'lat': 34.0446466197085, 'lng': -118.2536786802915}}},
  'place_id': 'ChIJh_dVskrGwoARddqbvhmoZfg',
  'plus_code': {'compound_code': '2PWX+93 Los Angeles, California, United States',
   'global_code': '85632PWX+93'},
  'types': ['street_address']}]

Upvotes: 0

Views: 222

Answers (2)

Vikramaditya Gaonkar
Vikramaditya Gaonkar

Reputation: 717

I see a few issues with the code that you have written:

  1. The lat_long_list = [] should be inside the function definition.
  2. you are running multiple for loops inside the function which is not necessary

With python, you can make the code much more readable by doing something like this:

def geocode_results_process(x):
    lat_long_list = []
    for list_item in x:
        for item in list_item:
            latitude= item['geometry']['location']['lat']
            longitude = item['geometry']['location']['lat']
            lat_long_list.append("{},{}".format(latitude, longitude))

I would recommend reading this https://thispointer.com/python-how-to-unpack-list-tuple-or-dictionary-to-function-arguments-using/ to get started with unpacking lists in python

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

Looks like you are missing some data in from geocode_result

Use

def geocode_results_process(x):
    lat_long_list = []         
    for item in x:
        for sub_item in item:
            list_component = sub_item['geometry']['location']
            latlong = str(list_component['lat']) + ',' + str(list_component['lng'])
            lat_long_list.append(latlong)
    return lat_long_list

Note:

  • You can directly iterate your list and can skip range here.
  • No need to iterate the dict. You can directly access the value using the key

Upvotes: 1

Related Questions