Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use reduce with dictionary

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?

like image 373
Salvador Dali Avatar asked Oct 27 '14 08:10

Salvador Dali


People also ask

How do you reduce a dictionary in python?

Function Signature of Python Reduce reduce() takes: function : the first argument that defines the function to apply, also known as the predicate of reduce function. iterable : the second argument with the values to be passed to function. initializer : the third argument, that is the value to start with.

How do you add to a dictionary in python?

Python add to Dictionary using “=” assignment operator We do not have any specific Python way to update a dictionary. If you want to add a new key to the dictionary, then you can use the assignment operator with the dictionary key. This is pretty much the same as assigning a new value to the dictionary.


1 Answers

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)
like image 108
Abhijit Avatar answered Oct 17 '22 18:10

Abhijit