Python dictionary from lambdas

I created a python dictionary for 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 in the ('a', 'b', 'c')

dictionary, the lambda function takes a parameter and counts how many times that particular letter appears. This works great. The problem is I am trying to do it with a dictionary comprehension ...

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

      

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

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

      

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

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

      

All lambdas seem to count how many times a letter 'c'

(!) Appears and not other letters.
Can anyone please explain to me why? How can we do this in a loop?

+3


source to share





All Articles