Python2 - Summing "for" loop output
Question: I'm trying to make a script that takes a balances of multiple addresses from a
json file and adds them together to make a final balance.

This is the code so far -

    
    
    import json
    from pprint import pprint
    
    with open('hd-wallet-addrs/addresses.json') as data_file:    
        data = json.load(data_file)
    
    for balance in data:
        print balance['balance']
    

  

**This is what's in the json file:**

    
    
    [
        {
            "addr": "1ERDMDducUsmrajDpQjoKxAHCqbTMEU9R6",
            "balance": "21.00000000"
        },
        {
            "addr": "1DvmasdbaFD7Tj6diu6D8WVc1Bkbj7jYRM",
            "balance": "0.30000000"
        },
        {
            "addr": "18xkkUi7qagUuBAg572UsmDKcZTP5zxaDB",
            "balance": "0.80000000"
        },
        {
            "addr": "1MmTDCsySdsWRVbNFwXBy2APW5kGsynkaA3",
            "balance": "0.005"
        },
    
    ]
    

The output is like this:

    
    
    21
    0.3
    0.8
    0.005
    

How should I edit my code to add the numbers together?


Answer: Actually add them together...

    
    
    total = 0
    for balance in data:
        total += float(balance['balance'])
    print total
    

Or using `sum`:

    
    
    print sum(float(temp_balance['balance']) for temp_balance in data)
    

