Python: Dispatching Functions From A Dictionary

I was updating the Readme files for some of my python projects and started looking through my Mood Tracker code.  While reading over it, I couldn’t help wondering: “Could you cut out the If/Else statements in the menu, and call the functions from a dictionary instead?”

Turn’s out the answer’s Yes!!

Here’s how you Dispatch A Function From A Dictionary In Python


Update: I rewrote my code!  Here’s what it looked like before – and here’s what it looks like now:

def menu():
    """Main Menu"""

    menu_dict = {
        '1': log_mood,
        '2': view_history,
        '3': quote_of_the_day,
        '4': delete_log_entry,
        '5': delete_entire_history,
        '6': quit
    }

    menu_choice = input("1.  Log Your Mood \n2.  View Your History \n3.  Quote of the Day \n4.  Delete Log Entry \n5.  Delete Entire History \n6.  Quit\n\n")
    
    # Figure out how to make this work with **kwargs 
    # So I don't have to global date/time in log_mood()
    try:
        menu_dict[menu_choice]()
    except KeyError:
        print("Please pick a valid option")
        menu()

(If you want to see the whole code (Including the before & after samples), click here

Advertisements
Python: Dispatching Functions From A Dictionary

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s