PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] How do I implement a lambda function inside a dict/set/list

 November 04, 2022     dictionary, lambda, python     No comments   

Issue

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?


Solution

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
}


Answered By - Samwise
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing