Home > Enterprise >  TypeError when trying to get the last 5 objects from a JSON
TypeError when trying to get the last 5 objects from a JSON

Time:12-09

import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}

url = f'https://.......'
response = requests.get(url, headers=headers).json()
graphs = response['graphPoints']
soma = sum(abs(d["value"]) for d in graphs["graphPoints"][-5:])

print(soma)
soma = sum(d["value"] for d in graphs["graphPoints"][-5:])
TypeError: list indices must be integers or slices, not str

How can I solve this TypeError?

Note: In other response from this same API, this error does not appear, but I couldn't find what sets it apart and what is creating such a problem..

Note 2: I honestly found other questions here in the community about this same typified error, but I couldn't understand how to solve them in my specific case.

CodePudding user response:

You don't need read graphPoints twice, replace

soma = sum(d["value"] for d in graphs["graphPoints"][-5:])

with

soma = sum(d["value"] for d in graphs[-5:])
  • Related