【问题标题】:KeyError: 0 on an api requestKeyError: 0 在 api 请求上
【发布时间】:2020-02-25 23:49:04
【问题描述】:

我正在 google 地方运行一个 api 请求,并且遇到了 keyerror 0 的问题。我不确定从那里去哪里。 这是我的代码:

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

【问题讨论】:

  • parameters = f"radius=5000&type=hotel"f在那里做什么?

标签: python api keyerror


【解决方案1】:

不要在城市数量范围内循环并在不同索引处读取城市,而是尝试使用for...in python 循环,如下所示:

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

这可能会阻止您在尝试读取索引 0 处的值时遇到 KeyError。

【讨论】:

    【解决方案2】:

    keyerror 0 出现是因为在这一行

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

    您正在尝试访问 cities 值,就像 cities 是一个列表一样,也就是说,通过传递数字参数,而不是传递关键参数(字符串),这是正确方法之一访问字典值。

    按照 N. Solomon 的建议,您应该遍历 cities 键,这样计数器变量会直接分配给您需要传递给 cities 字典以获取其值的键(字符串)。

    【讨论】:

      猜你喜欢
      • 2015-05-31
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 2019-12-07
      • 2021-11-22
      • 1970-01-01
      相关资源
      最近更新 更多