【问题标题】:Sorting through API data, says list indices must be integers or slices, not strings通过 API 数据排序,表示列表索引必须是整数或切片,而不是字符串
【发布时间】:2023-02-26 16:46:02
【问题描述】:

试图对 api 数据进行排序。但是得到一个错误

“TypeError:列表索引必须是整数或切片,而不是 str”

尝试从字典中打印某些键的某些值时。它说容器是一个字典,但要求列表索引是整数或切片,这对我来说没有意义,因为它是一个字典。

我的代码:

import requests
import json


url = "https://api-football-v1.p.rapidapi.com/v3/teams"

querystring = {"league":"39","season":"2022"}

headers = {
    "X-RapidAPI-Key": "1b6ce2494dmshf74f9c461b4cdbbp1d3b11jsndd6ab0d8575c",
    "X-RapidAPI-Host": "api-football-v1.p.rapidapi.com"
}

response = requests.request("GET", url, headers=headers, params=querystring)
response = response.json()

print(type(response))
print(response)
print(response["response"]["team"]["id"] + response["response"]["team"]["name"])

输出:

<class 'dict'>

{'get': 'teams', 'parameters': {'league': '39', 'season': '2022'}, 'errors': [], 'results': 20, 'paging': {'current': 1, 'total': 1}, 'response': [{'team': {'id': 33, 'name': 'Manchester United', 'code': 'MUN', 'country': 'England', 'founded': 1878, 'national': False, 'logo': '}.....................

Traceback (most recent call last):
  File "E:\Dropbox\CG\Coding\music_api\main.py", line 27, in <module>
    print(response["response"]["team"]["id"] + response["response"]["team"]["name"])
TypeError: list indices must be integers or slices, not str

【问题讨论】:

    标签: python api


    【解决方案1】:

    响应对象是一个字典,但response["response"] 是一个列表。

    ...'response': [{'team': {'id': 33,...
    

    注意[。试试response["response"][0]["team"]["id"],如果你有兴趣处理列表中的所有字典,或者一个 for 循环,以防可能有多个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-19
      • 2016-09-16
      • 2017-10-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      • 2016-05-25
      相关资源
      最近更新 更多