How to add values from a json request in python?

0

Example:

request = requests.get('https://api.amountofsomething.com')
amount = request.json()['amount']

This request returns values like these:

[{"amount": 0.1}, {"amount": 2},{"amount": 145},{"amount": 5.84}]

I need to make sums, without patterns, of different index values. I have done so, and it worked, but for large amounts of data the code gets very large.

amount0 = amount[0]['amount']

amount1 = amount[1]['amount']

amount2 = amount[2]['amount']

sum0 = amount0 + amount2 > > > sum0 = 0.1 + 145

...

I tried different ways to manipulate this data to generate fewer codes.

sum0 =  amount [0+2]['amount']

sum1 = amount [[0] + [2]]['amount']

sum2 = amount [0]['amount'] + amount [2]['amount']

None of these options worked, can anyone give me a hand?

    
asked by anonymous 09.08.2018 / 20:10

3 answers

2

If your answer comes in the form:

amounts = [{"amount": 0.1}, {"amount": 2}, {"amount": 145}, {"amount": 5.84}]

And you need to add all the values, just do:

total = sum(it['amount'] for it in amounts)

So, it will count independently of the amount of items that come in the response.

    
09.08.2018 / 20:16
1

Considering that you have a list of dictionaries returning in this api we have:

amounts = [
        {"amount": 0.1},
        {"amount": 2},
        {"amount": 145},
        {"amount": 5.84}
    ]

You could iterate over this list by adding the indexes.

soma = 0

for amount in amounts[0:15]:
    soma += amount.get("amount",0)

Or use list comprehension

soma = sum(amount.get("amount",0) for amount in amounts[0:15])

EDIT: Change to only add the first 15 indexes of the returned data.

The count of items starts at 0 and goes to max-1, in case 15-1 = 14 ... So index 0 through 14 are 15 values.

    
09.08.2018 / 20:16
0

You have several dictionaries within a list, so we can access these dictionaries with a for:

req = [{"amount": 0.1}, {"amount": 2},{"amount": 145},{"amount": 5.84}]

soma = 0
for dic in req:
    soma += dic['amount']

>>> print soma
152.94

Edit:

Look closely

req[0] = {"amount": 0.1} #Primeiro item da lista é um dicionario
req[1] = {"amount": 2}

req[0]['amount'] = 0.1 #Assim acessamos o valor
req[1]['amount'] = 2

Then, to add only the first 2 indexes, for example, we can do:

soma = 0
for i in range(0,2):
    soma += req[i]['amount']

>>> print (soma)
2.1
    
09.08.2018 / 20:14