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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With