简体   繁体   中英

Sum of dictionary values in python and coming up with “unsupported operand type” error

I have this dictionary:

result = {'kid': ['$6.00', '$159.00', '$10.00'], 
          'entertainment': ['$2.40', '$3.10', '$30.37', '$40.15'], 
          'food': ['$5.04', '$8.00', '$160.15'], 
          ... }

I'm trying to write code that will add up the amounts of each value and print it next to the corresponding key, with a result such as this:

['kid': '$175', 'entertainment': '$76.02', 'food': '$249.21', .... etc.] 

I've used the following code and variations of it, trying to get a sum of the values.

sumCat={}

for k, v in result.items():
    sumCat[k] = sum(v)

print(sumCat)

But I always get this error message:

unsupported operand type(s) for +: 'int' and 'str'

I don't understand the message.

You're using "sum" on a list of strings. You have to convert each to an numeric value, add those and then convert to the form you want.

I suggest that you deal with only the values; leave the $ for output formatting.

You can use a dictionary comprehension:

result = {'kid': ['$6.00', '$159.00', '$10.00'], 'entertainment': ['$2.40', '$3.10', '$30.37', '$40.15'], 'food': ['$5.04', '$8.00', '$160.15']}
final_result = {a:"$ {}".format(round(sum(float(i[1:]) for i in b), 2)) for a, b in result.items()}

Output:

{'kid': '$ 175.0', 'entertainment': '$ 76.02', 'food': '$ 173.19'}

The problem here is that you're trying add strings together -- notice how the prices in your original answer are in quotes and have the $ symbol, they're not just numbers!

The way to solve this is to account for that in your adding. I'd avoid using the sum method here as it's not really designed for handling input like this. Here's one way to do it:

sumCat={}

for k, v in result.items():
    summed_vals = 0
    for price in v:
        if '-' in price:
            # takes into account the dollar sign/negative sign
            summed_vals -= float(price[2:])         
        else:
            summed_vals += float(price[1:]) # takes into account the dollar sign
    sumCat[k] = format(summed_vals, '.2f') # rounds to nearest cent

print(sumCat)

#output
{'food': '173.19', 'kid': '175.00', 'entertainment': '76.02'}

You can use a dictionary comprehension with str.strip and float to convert your strings into numeric data which can be summed.

d = {'kid': ['$6.00', '$159.00', '$10.00'], 
     'entertainment': ['$2.40', '$3.10', '$30.37', '$40.15'], 
     'food': ['$5.04', '$8.00', '$160.15']}

res = {k: sum(map(float, (i.strip('$') for i in v))) for k, v in d.items()}

Result:

{'entertainment': 76.02,
 'food': 173.19,
 'kid': 175.0}

Just remove the $ and use just map() .

result = {'kid': ['6.00', '159.00'], 'entertainment': ['2.40','40.15']}
sumCat={}

for k, v in result.items():
   sumCat[k] = sum(map(float,v))

print(sumCat)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM