LTzycLT LTzycLT - 1 year ago 172
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download