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
python lambda


source to share


No one has answered this question yet

Check out similar questions:

5504
Does Python have a ternary conditional operator?
5231
What are metaclasses in Python?
4473
Calling an external command in Python
4268
How to combine two dictionaries in one expression?
3602
Does Python have a substring method "contains"?
3428
How to sort a dictionary by value?
2683
Check if the given key exists in the dictionary
2679
Iterating over dictionaries using 'for' loops
2369
Add new keys to the dictionary?
826
Why is Python lambdas useful?



All Articles
Loading...
X
Show
Funny
Dev
Pics