To access JSON I use:
url = f'https:...........'
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:
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.
CodePudding user response:
What you need is simple generator expression with a slice:
>>> sum(d["value"] for d in graphs["graphPoints"][-5:])
31