How to access a function within a python dictionary?

Asked

Viewed 88 times

2

We have the following functions:

def oi():
    print('oi')

def ola():
    print('ola')

Now let’s store them inside a dictionary as follows:

saudacoes = {

    'chegada':{
        'simples': oi(),
        'cult': ola(),
    }

}

I need to access the functions depending on two user inputs, the first says whether it is an arrival or farewell greeting and the second which greeting will be, so:

tipo, qual = input().split()
saudacoes[tipo][qual]

Let’s assume the user type:

> chegada simples

Therefore, the program should search in the dictionary as follows:

saudacoes[chegada][simples]

And you would expect him to perform the function oi(). But nothing happens. Where I’m going wrong?

1 answer

4


When you do oi() (with the parentheses) is calling the function (i.e., is running it) and its return is placed as the dictionary value. But since you didn’t put any return in it, then it returns None.

But the functions are already executed when the dictionary is created, so much so that the code already prints "hi" and "hello" when creating the dictionary.

If you want to save your own function for it to be executed later, remove the parentheses:

saudacoes = {
    'chegada':{
        'simples': oi, # sem os parênteses 
        'cult': ola # sem os parênteses 
    }
}

And only use the parentheses when calling her:

tipo, qual = input().split()
saudacoes[tipo][qual]()

That’s because saudacoes[tipo][qual] refers to a function, and the parentheses serve to call this function.

Browser other questions tagged

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