python dictionary of lambdas

114 views Asked by At

I've made a python dictionary of lambdas:

d['a'] = lambda x: x.count('a')
d['b'] = lambda x: x.count('b')
d['c'] = lambda x: x.count('c')

For each key ('a', 'b', 'c') of the dictionary a lambda function receive a parameter and count how many times appears that specific letter. This works wonderfully. The problem is when I try to make it with dictionary comprehension...

lst = ['a', 'b', 'c']
d = {k: lambda x: x.count(k) for k in lst}

... or even with a simple for-loop:

for i in lst:
    d[i] = lambda x: x.count(i)

The code runs, but when I try to call to a specific lambda, like:

print(d['a']('apple'))

it appears that all the lambdas count how many times the 'c' letter appears(!) and not the other letters.
Somebody can explain me why?
How can we make it in a for-loop?

0

There are 0 answers