处理足球API数据时遭遇'String indices must be integers'错误求助
问题
处理API返回数据时,访问字典出现TypeError: string indices must be integers错误,希望用字符串键访问字典(不使用整数索引,且整数索引会触发越界错误)。
相关代码:
import requests import json headers = { "X-RapidAPI-Key": "1b6ce2494dmshf74f9c461b4cdbbp1d3b11jsndd6ab0d8575c", "X-RapidAPI-Host": "api-football-v1.p.rapidapi.com" } url_stats = "https://api-football-v1.p.rapidapi.com/v3/teams/statistics" qstring_stats1 = {"league":"39","season":"2022","team":"33"} resp_stats = requests.request("GET", url_stats, headers=headers, params=qstring_stats1) resp_stats = resp_stats.json() print(type(resp_stats)) print(resp_stats) for team in resp_stats["response"]: print(str(team["team"]["id"]) + " - " + (team["team"]["name"])) print(resp_stats)
输出报错:
<class 'dict'> {'get': 'teams/statistics', 'parameters': {'league': '39', 'season': '2022', 'team': '33'}, 'errors': [], 'results': 11, 'paging': {'current': 1, 'total': 1}, 'response': {'league': {'id': 39, 'name': 'Premier League', 'country': 'England', 'logo': 'https://media.api-sports.io/football/leagues/39.png', 'flag': 'https://media.api-sports.io/flags/gb.svg', 'season': 2022}, 'team': {'id': 33, 'name': 'Manchester United'}............ Traceback (most recent call last): File "E:\Dropbox\CG\Coding\music_api\main.py", line 47, in <module> print(str(team["team"]["id"]) + " - " + (team["team"]["name"])) TypeError: string indices must be integers
错误原因
从输出的resp_stats结构能看到,resp_stats["response"]是单个字典,不是列表。你用for team in resp_stats["response"]遍历时,实际是在遍历字典的键(比如"league"、"team"这类字符串),此时team变量是字符串,再用team["team"]自然会触发"字符串索引必须是整数"的错误。
解决方法
直接通过字符串键访问response字典里的team数据即可,不需要循环:
# 替换原来的for循环部分 team_data = resp_stats["response"]["team"] print(f"{team_data['id']} - {team_data['name']}")
如果后续API可能返回多个结果(即response变成列表),可以先判断类型再兼容处理:
response = resp_stats["response"] if isinstance(response, list): for item in response: team_data = item["team"] print(f"{team_data['id']} - {team_data['name']}") else: team_data = response["team"] print(f"{team_data['id']} - {team_data['name']}")
内容的提问来源于stack exchange,提问作者formlessform
相关产品推荐
相关产品推荐

