6

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.

xxmbabanexx
  • 8,256
  • 16
  • 40
  • 60
user2097496
  • 267
  • 3
  • 10

2 Answers2

11

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
RocketDonkey
  • 36,383
  • 7
  • 80
  • 84
  • Wow, that may be the best example I've seen of a concise explanation in English that maps to a generator expression in such an obvious way that you don't even need to say that's what you're doing. Wish I could give more than +1. – abarnert Feb 22 '13 at 00:51
  • @abarnert Coming from you that is quite a compliment, thanks :) – RocketDonkey Feb 22 '13 at 02:49
1
>>> a = {'a' : 5, 'b': 8}
>>> sum(value for _, value in a.items() if value > 0)
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
Damgaard
  • 922
  • 1
  • 9
  • 17