I have some problem understanding how to use reduce with dictionaries in python. For example I have the following dictionary.
{1: 3, 2: 1, 3: 2}
and I am trying to calculate the following:
s = 0
for i in h:
s += h[i] * (h[i] - 1)
This works as expected (I get: 8
), but I my attempt to convert it to reduce paradigm fails:
reduce(lambda x, y: x + y * (y - 1), h)
, but I am getting the wrong answer.
I assume this is because I am using keys, not values. How can I convert my code to reduce properly?
You need to iterate over the dictionary while reducing it with an initial value of zero.
Note, iterating over a dictionary, actually iterates over the keys so you need to index the dictionary to get the value
reduce(lambda x, key:x + h[key] * (h[key] - 1), h, 0)
Alternatively, as you are only interested in the values of the dictionary, caring least about the key, just iterate on the values of the dictionary
reduce(lambda x, value:x + value * (value - 1), h.itervalues(), 0)
reduce(lambda x, value:x + value * (value - 1), h.values(), 0)