V
V
VuztreeCalan2018-07-20 16:57:10
Python
VuztreeCalan, 2018-07-20 16:57:10

How to make function execution by key from Python 3 dictionary?

There is a dictionary where each key is a letter and each value is a function. The user is prompted for a letter, how to execute the function that corresponds to the entered letter?
Example of non-working code:

def main():
    while True:
        key = str(input("Press R to read a file\nPress E to enter data\nPress L to leave the program\n"))
        key = key.lower()
        execute(key)

def execute(command):
    return {
        'r' : readfile(),
        'e' : enterdata(),
        'l' : exit()
    }.get(command, "Command not found")

def readfile():
    #Действия

def enterdata():
    #Действия

def exit():
    #Действия

main()

If I understand correctly, the code here returns the entire list, so the result of the execution will be that all functions act in turn.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
VuztreeCalan, 2018-07-20
@VuztreeCalan

UPD: Hurrah, solved! I had to bang my head, but it turned out gracefully

def main():
    while True:
        key = str(input("Press R to read a file\nPress E to enter data\nPress L to leave the program\n"))
        key = key.lower()
        execute(key)


def readfile():
    #Действия


def enterdata():
    #Действия


dictOfCommands = {
    'r': readfile,
    'e': enterdata,
    'l': exit
}


def execute(command):
    dictOfCommands[command]()


main()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question