How to add values of a json request in python?

Asked

Viewed 340 times

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 do sums, without patterns, of different index values. I have done so, and it has worked, but for large amounts of data the code gets very extensive.

amount0 = amount[0]['amount']

amount1 = amount[1]['amount']

amount2 = amount[2]['amount']

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

...

I tried in different ways, to manipulate this data to generate less code.

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

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

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

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

3 answers

2

If your answer comes from the way:

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

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

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

Thus, it will add up regardless of the amount of items that comes in the answer.

1

Assuming 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 that list by summing up the indices..

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 add only the first 15 indexes of the returned data.

The counting of items starts at 0 and goes up to max-1 , in case 15-1 = 14... Thus from index 0 to 14 are 15 values.

  • First of all, thank you for answering. With this code I get the return of the sum of all quantities, but in case I need to add for example the first 15 quantities , I would have to modify your code for this ?

  • Changed to your suggestion. Just added index count..

0

You have multiple 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 at

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

So to add up only the first two indices, for example, we can do:

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

>>> print (soma)
2.1
  • Thank you for the answer, with your code with the sum of all indexes , it would be possible for example to add up only the first 15 indexes ?

  • @Eliezerborges , see the edition I made

  • By your concept I managed to solve my problem. Thank you for taking your time and knowledge to help me.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.