Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Sum values in a dictionary based on condition

I have a dictionary that has Key:Values.

The values are integers. I would like to get a sum of the values based on a condition...say all values > 0 (i.e).

I've tried few variations, but nothing seems to work unfortunately.

like image 245
user2097496 Avatar asked Feb 21 '13 23:02

user2097496


2 Answers

Try using the values method on the dictionary (which returns a generator in Python 3.x), iterating through each value and summing if it is greater than 0 (or whatever your condition is):

In [1]: d = {'one': 1, 'two': 2, 'twenty': 20, 'negative 4': -4}

In [2]: sum(v for v in d.values() if v > 0)
Out[2]: 23
like image 136
RocketDonkey Avatar answered Oct 16 '22 03:10

RocketDonkey


>>> a = {'a' : 5, 'b': 8}
>>> sum(value for _, value in a.items() if value > 0)
like image 31
Damgaard Avatar answered Oct 16 '22 05:10

Damgaard