Search code examples
pythonfunctiondictionaryhashmap

Is there any other ways to accomplish this task in Python?


This might be a silly question, but I was wondering if I could accomplish this task using a dictionary or some sort of array? I tried using a dictionary like this, and it just calls all functions.

My goal is to call a specific function if a keyword is input by the user, but I want to avoid using those lengthy if and else statements.

Here is what I have tried:

def Func1():
    print ("This is func1")

def Func2():
    print ("This is func2")

def Func3():
    print ("This is func3")

functions = {"/func1" : Func1(), "/func2" : Func2(), "/func3" : Func3()}


Solution

  • Make a dictionary that contains the function objects but does not actually call them:

    def func1():
        print("I am function 1")
    
    # etc for func2 and func3
    
    functions = {
        "func1": func1,
        "func2": func2,
        "func3": func3
    }
    answer = input("Which function do you want to call? ")
    if answer in functions:
        # find the correct function object and call it
        functions[answer]()
    else:
        print("I can't find that function.")