Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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:])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading