Ask coding questions

← Back to all posts
how to make dictionary act like if statement?
TerrorbuildLuna (38)

Hi, I'm making list of commands for a project I've been working on in Python. I would like to make it into a "dictionary" command list instead of using if statements. So far, I've got something like this (there are more commands than this in my actual code):

list1 = "Something"
list2 = "Something"
list3 = "Something"

list = [list1,list2,list3]

cmds = {

while True:
Problem is, python doesn't know that I don't want to call the input function at the start of the program, but when command 1 is called by the input from the code "cmds[input()]"

Is there any other way? Or will I have to go back to good ol' if statement? Please help if you think you know an answer.

Answered by Coder100 (16868) [earned 5 cycles]
View Answer
Coder100 (16868)

never ever use an if statement for this!

You are going in the right path, just you had a tiny logic error!
Put them inside a function so they get invoked instead:

def my_func():
  return "my_func called"

cmds = {
  "whatever": lambda: print(int(input())),
  "embedded example": my_func
  # do you understand or do you need more examples

while True:
  output = cmds[input()]()
  # btw, you can also use the output value
  if output == "my_func called":
    print("my_func called, how was it?")

Remember: if it can be run, it gets run.

TerrorbuildLuna (38)

@Coder100 Thank you! It works, but I don't really get the "()" at the end of "cmds[input()]". Could you clear that up for me?

Coder100 (16868)

you know how you do input()? the () calls input the function. Because cmds[input()] is a 'function' (if done correctly), we use () to do it @TerrorbuildLuna

TerrorbuildLuna (38)

@Coder100 Ah, I get it, because I use functions in my dictionary?

DynamicSquid (4626)

First create a function to do what you want. Then do this:

def some_function():
  # do something

def another function():
  # another function

cmds = {
  "cmd1" : some_function, # notice it doesn't have the open brackets
  "cmd2" : another_function


You can read this post for more information

TerrorbuildLuna (38)

@DynamicSquid Thank you for providing an equally useful answer as to @Coder100. However, I hope you do not mind that I marked Coder100's answer as the correct answer. If I need to give an excuse, I'd say that I saw Coder100's answer first. Sorry!