You could use the built-in sum
function:
sum(v for v in color_codes.itervalues() if v > x)
The argument to sum
is a generator expression, and the result is the sum of the values that are greater than x
.
Domanda
I was wondering what is a nice, elegant pythonic way to run a sumif on values of keys in a dictionary that adhere to a certain condition. For example, this dict:
color_codes = {'red':1,'yellow':2, 'green':3, 'brown':4, 'blue':5, 'pink':6, 'black': 7}
lets say I want the sum of all the values of the keys, given that the value is >= a certain number x. How would you go about it? Anonymous function maybe?
Thanks in advance for your help
Soluzione
You could use the built-in sum
function:
sum(v for v in color_codes.itervalues() if v > x)
The argument to sum
is a generator expression, and the result is the sum of the values that are greater than x
.