I've been trying to store and then call a string and/or a function inside a dictionary.
First example
def mainfunction():
dict = {
'x' : secondfunc,
'y' : 'hello world'
}
while True :
inpt = input('@')
dict[inpt]()
def secondfunc():
print('hi world')
mainfunction()
This works only if I input the key 'x'. If I try to input key 'y', I get this error.
TypeError: 'str' object is not callable
Also, the problem with this method is that it can't make a default answer.
Second example
def mainfunction():
dict = {
'x' : secondfunc,
'y' : 'hello world'
}
while True:
inpt = input('@')
z = dict.get(inpt, 'Default text')
print(z)
def secondfunc():
print('hi world')
mainfunction()
This method works for key 'y', but for key 'x' it prints something to the effect of:
<function secondfunc at 0x7ab4496dc0>
I'm trying to make it so that whichever value I input, it will either print a default value, print a string, or execute a function. All depending on the key input.
Last example
The only solution I've found is that which uses if
statements.
def mainfunction():
dict = {
'x' : secondfunc,
}
dict2 = {
'y' : 'hello world'
}
while True:
inpt = input('@')
z = dict2.get(inpt, 'Default text')
if inpt == 'x':
dict[inpt]()
else:
print(z)
def secondfunc():
print('hi world')
mainfunction()
This solution takes more code than I would like it to, and it also requires an if
statement specific to the dictionary given, which takes more time.
Is there no better way to do this?