Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python add value in dictionary in lambda expression

Tags:

python

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
like image 587
LTzycLT Avatar asked Sep 20 '16 12:09

LTzycLT


People also ask

Can you add values to a dictionary in python?

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.

Can you append values to a dictionary?

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.

Can lambda expressions contain statements Python?

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.


1 Answers

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.

like image 194
Łukasz Rogalski Avatar answered Oct 17 '22 14:10

Łukasz Rogalski