Lambda function dictionary update

Updating a dictionary using lambda function doesn’t take d[‘key’]=‘value’ instead it only considers d.update({‘key’:‘value’}) within the lambda function.
When you update a dictionary using normal method. you can do it so
by d[‘key’]=‘value’
But the same method doen’s work when using lambda function
lambda x,y: d[‘x’]=y for x,y in args / kwargs
Instead it takes this as
lambda x: d.update({‘x’,y}) for x,y in args/kwargs

I’ve found about it recently , i want to make a suggestion if the d[‘x’]=y can be implemented in lambda function. Please let me know if this found and idea is useful and anything else that can be notified on it.

A lambda defines a simple function without its own name. That’s why it is used mainly when there is no need to refer to it by name, often as an argument in a function call. You could bind a name to a lambda by storing it in a variable, but PEP-8 recommends against it.

A lambda is limited to a single expression. The reason an assingnment like d[key]=value cannot be used is that it’s a statement, not an expression.

If those two limitations do not fit the intended usage, a regular function def funcname(...): should be used instead.

The advantage of lambdas and probably the reason for their existence is they are “light-weight” - short and in one line. Proposing to enhance the lambdas to be as capable as regular functions goes in the opposite direction.

3 Likes

No, that doesn’t work, either. Has syntax errors and args and kwargs would be undefined. Better fix that so we know what case you actually have.

2 Likes