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
You can add data or values to a dictionary in Python using the following steps: First, assign a value to a new key. Use dict. Update() method to add multiple values to the keys.
Appending element(s) to a dictionary To append an element to an existing dictionary, you have to use the dictionary name followed by square brackets with the key name and assign a value to it.
In particular, a lambda function has the following characteristics: It can only contain expressions and can't include statements in its body. It is written as a single line of execution.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With