Perform function according to dictionary key

Asked

Viewed 56 times

-2

I want the user to choose an option and according to the chosen option the system performs a specific function. I wanted a more generic solution without a lot of if, elif and else. I thought of joining the solution to a dictionary, working more or less like this:

def funcao1():
    ...
    return ...

def funcao2():
    ...
    return ...

     .
     . 
     .

dicionario_funcoes = {1: funcao1(), 2: funcao2(), 3: funcao3() ... }

escolha = int(input('Escolha uma opcao: '))

lista_funcoes[escolha]

But this does not work, does not execute the function as the choice is made.

  • 1

    what is the doubt?

1 answer

2


You cannot use functions directly like this, because when creating the dictionary is calling the function, then the value stored in the key will be the result of the function that is called, and then nothing will work.

You have to store a function you want to call without the call occurring. With this you cannot use the parentheses which is the call operator, store only the function identifier in the dictionary.

Then when calling the function you should apply the parentheses, because it is they who make the call occur using that identifier. And this identifier can be used with a variable, as I was trying to do, I just didn’t know what to call.

def funcao1():
    return 1
def funcao2():
    return 2

dicionario_funcoes = { 1: funcao1, 2: funcao2 }
escolha = int(input('Escolha uma opcao: '))
print(dicionario_funcoes[escolha]())

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I’m not making robust code, I’m just showing the mechanism.

Every syntax of the language has a reason to exist that way, and knowing why it’s there can learn the right way. Things do not exist in the language by chance or because it is cute, was thought and is in the documentation how everything works. In the case of parentheses used immediately after an identifier or a value that delivers an identifier is the operator function call, where to use it depends on what you want (use when you want to call, do not use if the intention is not to call). It’s not just there to look beautiful, it has a specific function and can be used in various contexts, as well as the + is so, or other operators.

  • Truth, I didn’t notice that in the end I was calling the function and needed to execute it, so I forgot the parentheses, thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.