简体   繁体   中英

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())

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM