Home > Enterprise >  How do I implement a lambda function inside a dict/set/list
How do I implement a lambda function inside a dict/set/list

Time:08-15

So I am coding a user-input system that can accept commands. Further detail on it won't be revealed.

One of the things I want to do is implement a lambda function inside a dictionary.

Here's an example of what I want to do:

dictionary = {

   "command_a": lambda:

               stuff_to_do = ""
               # do stuff 
               return stuff_to_do
   
}

And when the user enters `command_a', it'd call the function, as follows:

command = input("Command")
if command in dictionary.keys():
  dictionary[command]()

But I get:

  File "<stdin>", line 5
    stuff_to_do = ""
                ^
SyntaxError: invalid syntax

The code seems logical. The dictionary stores a function under the "command_a" key, but it doesn't work. Is it permissible to do so in python? If yes, then how to?

CodePudding user response:

A lambda can only define a function in the form of a single expression, e.g.:

dictionary = {
   "command_a": (lambda: "stuff to do")
}

If you want to define a function that consists of multiple statements, you need to use a def statement:

def command_a():
    stuff_to_do = ""
    # do stuff 
    return stuff_to_do
   
dictionary = {
   "command_a": command_a
}
  • Related