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?
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.
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.
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)
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