how to use reduce with dictionary

Salvador Dali picture Salvador Dali · Oct 27, 2014 · Viewed 28k times · Source

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?

Answer

Abhijit picture Abhijit · Oct 27, 2014

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

Python 2.X

reduce(lambda x, value:x + value * (value - 1), h.itervalues(), 0)

Python 3.X

reduce(lambda x, value:x + value * (value - 1), h.values(), 0)