Python adds value in dictionary in lambda expression

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

That is, to implement a lambda that has a similar function, as shown below.

def add_value(dict_x):
    dict_x['a+b'] = dict_x['a'] + dict_x['b']
    return dict_x
+4
source share
2 answers

Technically, you can use a side effect to update it and use that Nonereturned from .updateis false to return a dict through based on logical operations:

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

I just don’t see the reasons for this in real code, although with both a lambda and a function you wrote.

+6
source

dict, dict, __setitem__. . Python.

class MyCustomDict(dict):
    def __setitem__(self, key, item): 
        # your method here
0

Source: https://habr.com/ru/post/1655186/


All Articles