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

Sum the last five objects of a JSON

To access JSON I use:

url = f'https://api.sofascore.com/api/v1/event/9625897/graph'
response = requests.get(url, headers=headers).json()
graphs = response['graphPoints']
for graph in graphs:
    sum_value = graph['value']

This JSON can change size, so the last five "value" I’m trying to sum won’t always be in the same position, so I can’t specify exactly which position:

https://api.sofascore.com/api/v1/event/9625897/graph

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

In this case, the sum would give the result 31

[
  ...
  {'minute': 87, 'value': 4},
  {'minute': 88, 'value': 4},
  {'minute': 89, 'value': 4},
  {'minute': 90, 'value': 4},
  {'minute': 90.5, 'value': 15}
]

If I wanted to sum all the 92 "value", I could create a list:

List_Of_Values = []
List_Of_Values.append(graph['value'])

But in case I will always only need the last 5 "value", how could I do that?

Remembering that this JSON can contain different sizes, so I can’t specify in which position the last 5 will be fixed.

>Solution :

What you need is simple generator expression with a slice:

>>> sum(d["value"] for d in graphs["graphPoints"][-5:])
31
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