Skip to content
Sign UpLog In
This post is read-only. Explore Repls and connect with other creators on Community.View Community
The info in this post might be out of date, check out our docs instead. View docs
1

how to make dictionary act like if statement?

TerrorbuildLuna
TerrorbuildLuna

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 = {
"cmd1":print(int(input())),
"cmd2":print("ok"),
"cmd3":print(input())
}

while True:
cmds[input()]
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.

2 years ago

Voters

Comments

TopNew
1
Coder100
Coder100

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(): print("hi") 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.

2 years ago
1
TerrorbuildLuna
TerrorbuildLuna

@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?

2 years ago
1
Coder100
Coder100

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

2 years ago
1
TerrorbuildLuna
TerrorbuildLuna

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

2 years ago
1
DynamicSquid
DynamicSquid

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 } cmds["cmd1"]()

You can read this post for more information

2 years ago
2
TerrorbuildLuna
TerrorbuildLuna

@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!

2 years ago
Load more