Reputation: 480
I'm trying to make a dictionary of lambda functions. It should be able to take a key and process whichever function is bound to that key and output the result.
func_dict = {
"func1" : (z = lambda x, y: x + y),
"func2" : (z = lambda x, y: x * y)
} # include benchmark functions
func = input("Choose a function: ")
output = func_dict[func](3, 5)
print(output)
That sample should print 8
but it doesn't run and simple gives me can't assign to dictionary display
error on
{
"func1" : (z = lambda x, y: x + y),
"func2" : (z = lambda x, y: x * y)
}
(indentation doesn't seem to be the problem)
I'd like to avoid using eval()
& exec()
if possible.
Upvotes: 4
Views: 436
Reputation: 33
Your dictionary is fine dude.
func_dict = {
"func1" : lambda x, y: x + y,
"func2" : lambda x, y: x * y
} # include benchmark functions
func = input("Choose a function: ")
output = func_dict[func](3, 5)
print(output)
Upvotes: 1
Reputation: 10329
I think your assignment of z =
is what's broken.
Try
func_dict = {
"func1" : lambda x, y: x + y,
"func2" : lambda x, y: x * y
} # include benchmark functions
Here's it working for me:
❯❯❯ python
Python 3.6.7 (default, Dec 3 2018, 11:24:55)
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.10.44.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> func_dict = {
"func1" : lambda x, y: x + y,
"func2" : lambda x, y: x * y
} # include benchmark functions... ... ...
>>> func_dict["func1"](1,2)
3
Upvotes: 5
Reputation: 20490
Your initial attempt is going to raise a syntax error.
Instead you would want to assign the definition of your lambda function directly to the key as follows
#The lambda function is assigned as a value of the keys
func_dict = {
"func1" : lambda x, y: x + y,
"func2" : lambda x, y: x * y
}
func = input("Choose a function: ")
output = func_dict[func](3, 5)
print(output)
The output will be
Choose a function: func1
8
Choose a function: func2
15
Upvotes: 10