Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reduce python dictionary values if key meets condition

Tags:

python

I have a python dictionary with string keys, integer values. I want to find the sum of values if the key is not '?'. I can find the sum using a for loop like this.

d = {'a':20, 'b': 20, '?': 10}
sum = 0
for k in d.keys():
    if k != '?':
        sum += d[k]
print "This is my sum: " + sum

For ambition's sake only, I would really like to refactor that into a reduce() function. I took a stab at it:

sum = reduce(lambda s, k: s if k == '?' else s += d[k], d.keys())

but I don't really know what I'm doing. I'm sure someone with better functional chops than I can do this in minutes. Help me out?

like image 945
Guy Avatar asked Jan 31 '16 12:01

Guy


Video Answer


2 Answers

You can just use the built-in sum():

>>> d = {'a':20, 'b': 20, '?': 10}
>>> sum(value for key, value in d.items() if key != "?") 
40
like image 166
alecxe Avatar answered Oct 30 '22 14:10

alecxe


Since the key '?' can appear only one or zero times, just substract the value for that key from the sum:

>>> sum(d.values()) - d.get('?', 0)
40
like image 45
timgeb Avatar answered Oct 30 '22 13:10

timgeb