LTzycLT LTzycLT - 2 months ago 6
Python Question

python add value in dictionary in lambda expression

Is it possible to add values in dictionary in lambda expression?

That is to implement a lambda which has the similar function as below methods.

def add_value(dict_x):
dict_x['a+b'] = dict_x['a'] + dict_x['b']
return dict_x

Answer

Technically, you may use side effect to update it, and exploit that None returned from .update is falsy to return dict via based on boolean operations:

add_value = lambda d: d.update({'a+b': d['a'] + d['b']}) or d

I just don't see any reason for doing it in real code though, both with lambda or with function written by you in question.

Comments