How to use a shortcut with a dictionary

I have a problem understanding how to use shorthand 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'm trying to convert it to reduce the paradigm: reduce(lambda x, y: x + y * (y - 1), h) , but I get the wrong answer.

I assume this is because I use keys, not values. How can I convert my code correctly?

+5
source share
1 answer

You need to iterate over the dictionary, decreasing it with an initial value of zero.

Note dictionary iteration, actually key iteration, so you need to index the dictionary to get the value

 reduce(lambda x, key:x + h[key] * (h[key] - 1), h, 0) 

Alternatively, since you are only interested in the dictionary values ​​that care the least for the key, just iterate over the dictionary values

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) 
+18
source

Source: https://habr.com/ru/post/1205583/


All Articles