[Tutor] Using a dictionary in a menu implementation.

boB Stepp robertvstepp at gmail.com
Tue Jun 22 20:05:32 EDT 2021


On Tue, Jun 22, 2021 at 5:18 PM Ed Connell <edwinconnell at gmail.com> wrote:

> For a long time my menus were implemented like this:
>
> Menu = '[D]elete  [E]dit  [Q]uit'
>
> task = getchar().upper()

Is "getchar()" your own function?  You don't specify what GUI
environment you are operating in.  I guess this is meant to be
pseudocode?

> 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 ]  )

The problem with creating the dictionary this way is that you are
essentially hard-coding the values of "id", "size", and "age" to
whatever they happen to be at the time of the dictionary's creation.
I doubt that is what you want, and probably why the examples you saw
either had no arguments or used the same one since they didn't need it
to change in the latter case.  But it is okay to just associate the
keys with the desired function arguments to get this dictionary:  D =
{'D': delete, 'E': edit, 'Q': sys.exit}

So, to take this approach you would have to come up with a way to add
the appropriate arguments to get

1) D['D'](id)
2) D['E'](id, size, age)
3) D['Q']()

I don't know enough to suggest what the "standard" way to this would
be, assuming such a standard way exists.

HTH,
boB Stepp


More information about the Tutor mailing list