Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing lambdas in a dictionary

I have been trying to create a dictionary with a string for each key and a lambda function for each value. I am not sure where I am going wrong but I suspect it is either my attempt to store a lambda in a dictionary in the first place, or the fact that my lambda is using a shortcut operator.

Code:

dict = {     'Applied_poison_rating_bonus':          (lambda target, magnitude: target.equipmentPoisonRatingBonus += magnitude) } 

The error being raised is SyntaxError: invalid syntax and pointing right at my +=. Are shortcut operators not allowed in lambdas, or am I even farther off track than I thought?

For the sake of sanity, I have omitted hundreds of very similar pairs (It isn't just a tiny dictionary.)

EDIT:

It seems my issue was with trying to assign anything within a lambda expression. Howver, my issue to solve is thus how can I get a method that only knows the key to this dictionary to be able to alter that field defined in my (broken) code?

Would some manner of call to eval() help?

EDIT_FINAL:

The functools.partial() method was recommended to this extended part of the question, and I believe after researching it, I will find it sufficient to solve my problem.

like image 406
BlackVegetable Avatar asked Jan 19 '13 23:01

BlackVegetable


People also ask

What is lambda in dictionary in Python?

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.

Can you put a function in a dictionary Python?

In Python, everything is an object, so the dictionary can be passed as an argument to a function like other variables are passed.

Are lambdas faster than functions Python?

Being anonymous, lambda functions can be easily passed without being assigned to a variable. Lambda functions are inline functions and thus execute comparatively faster.

Should I use lambdas in Python?

In Python, we generally use Lambda Functions as an argument to a higher-order function (a function that takes in other functions as arguments). For Example, These are used together with built-in functions like filter(), map(), and reduce(), etc, which we will discuss later in this article.


Video Answer


1 Answers

You cannot use assignments in a expression, and a lambda only takes an expression.

You can store lambdas in dictionaries just fine otherwise:

dict = {'Applied_poison_rating_bonus' : (lambda target, magnitude: target.equipmentPoisonRatingBonus + magnitude)} 

The above lambda of course only returns the result, it won't alter target.equimentPoisonRatingBonus in-place.

like image 194
Martijn Pieters Avatar answered Sep 21 '22 05:09

Martijn Pieters