Python: conditional dictionary sum values

I have a dictionary that has Key:Values.

Values ​​are integers. I would like to get the sum of the values ​​based on the condition ... let's say all values ​​are> 0 (ie).

I tried several options, but nothing seems to work.

+5
source share
2 answers

Try using a method valuesin a dictionary (which returns a generator in Python 3.x), repeating each value and summing if it is greater than 0 (or regardless of your state):

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
+9
source
>>> a = {'a' : 5, 'b': 8}
>>> sum(value for _, value in a.items() if value > 0)
+1
source

All Articles