[Tutor] Using a dictionary in a menu implementation.

Ed Connell edwinconnell at gmail.com
Mon Jun 21 15:01:33 EDT 2021


Greetings!

For a long time my menus were implemented like this:

Menu = '[D]elete  [E]dit  [Q]uit'

task = getchar().upper()

if task == 'D':
    delete( id )
elif task == 'E':
    edit( id, size, age )
elif task == 'Q':
    sys.exit()

Then I saw examples which used a dictionary, but every example had no
arguments or always used the same argument. Obviously that would not work
for this example.  So I played around and came up with:

do = dict( D = [ delete, id ], E = [ edit, id, size, age ], [ Q = [
sys.exit ]  )

task = getchar().upper()

if task in do:
    n = do[task]
    n[0]( *n[1: ] )

Finally my question :) - how would you implement this menu using a
dictionary?  Is there a standard way to do this?

Thanks for all you do,

Ed Connell

-- 
I have a right and a left brain, but there is nothing right in the left one
and there is nothing left in the right one!


More information about the Tutor mailing list