Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using map and lambda to count frequency in a dictionary

So the task is rather simple. Read in a string and store each character and its frequency in a dictionary then return the dictionary. I did it rather easily with a 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 issue is that I need to rewrite this statement using a map and lambda. I've tried a few things, early attempts returned empty dictionaries ( code has been lost in the attempts ).

My latest attempt was ( in place of the for loop in above )

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

which returns a map object address.

Any suggestions?

like image 597
better_mixmaster Avatar asked Mar 08 '23 13:03

better_mixmaster


1 Answers

First, in python 3, you have to force list iteration on map

Then, your approach won't work, you'll get all ones or zeroes, because the expression doesn't accumulate the counts.

You could use str.count in a lambda, and map the tuples to a dictionary, that works:

txt = "hello"

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

result:

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

But once again, collections.Counter is the preferred way to do that.

like image 85
Jean-François Fabre Avatar answered Mar 21 '23 12:03

Jean-François Fabre