Using map and lambda to count frequencies in a dictionary

So, the task is quite simple. Read in a line and save each character and its frequency in the dictionary, and then return the dictionary. I made it pretty easy with the for loop.

def getInputFreq():
    txt = input('Enter a string value: ')
    d = dict()
    for c in txt:
           d[c] = d.get(c,0) + 1
    return d

The problem is that I need to rewrite this expression using map and lambda. I tried several things, early attempts returned empty dictionaries (the code was lost in attempts).

My last attempt was (instead of the for loop above)

 d = map((lambda x: (d.get(x,0)+1)),txt)

which returns the address of the map object.

Any suggestions?

+4
source share
1 answer

Firstly, in python 3 you must force iterate the list on map

Then your approach will not work, you will get all or zeros, because the expression does not accumulate counters.

str.count , :

txt = "hello"

d = dict(map(lambda x : (x, txt.count(x)), set(txt)))

:

{'e': 1, 'l': 2, 'h': 1, 'o': 1}

collections.Counter - .

+6

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


All Articles