lynch1234
lynch1234

Reputation: 31

KeyError: 0 on an api request

I'm running an api request on google places and am running into issues with a keyerror 0. I'm not sure where to go from there. Here is my code:

cities = df1['name']
parameters = f"radius=5000&type=hotel"
key  = g_key
url = "https://maps.googleapis.com/maps/api/nearbysearch/json?location="

for city in range(len(cities)):
    rr = requests.get(url + str(cities[city]) + parameters + "&key=" + key)
    responses.append(rr.json())

Upvotes: 2

Views: 721

Answers (2)

Tms91
Tms91

Reputation: 4144

The keyerror 0 occurs because at this line

for city in range(len(cities)):
    rr = requests.get(url + str(cities[city]) + parameters + "&key=" + key)  # <----this line
    responses.append(rr.json())

you are trying to access cities values as if cities were a list, that is, by passing it numeric arguments, rather than by passing it key arguments (strings), which is (one of) the correct way to access dictionaries values.

As suggested by N. Solomon, you should iterate through cities keys, in this way the counter variable is directly assigned the key (string) you need to pass to the cities dictionary to get its values.

Upvotes: 0

N. Solomon
N. Solomon

Reputation: 140

Instead of looping over the range of the number of cities and reading the city at different indexes try using for...in python loop as follows:

for city in cities:
    r = requests.get(f"{url}{city}&parameters&key={key}")
    responses.append(r.json())

This might prevent you from encountering the KeyError when trying to read the value at index 0.

Upvotes: 1

Related Questions