Sorting through API data, says list indices must be integers or slices, not strings

Question:

Trying to sort through api data. But getting an error

"TypeError: list indices must be integers or slices, not str"

When trying to print certain values of certain keys from a dict. It says the container is a dict, but is asking for list indices to be integers or slices, which doesnt make sense to me as its a dict.

My code:

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"])

OUTPUT:

<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:DropboxCGCodingmusic_apimain.py", line 27, in <module>
    print(response["response"]["team"]["id"] + response["response"]["team"]["name"])
TypeError: list indices must be integers or slices, not str
Asked By: formlessform

||

Answers:

The response object is a dict, but response["response"] is a list.

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

Note the [. Try response["response"][0]["team"]["id"], or a for loop if you are interested in handling all dicts in the list, in case there can be multiple.

Answered By: koobo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.