[Tutor] getting keyboard input to dictionary (newbie ques)

Paul Sidorsky paulsid@shaw.ca
Wed, 09 Jan 2002 22:59:40 -0700


Frank Holmes wrote:

> while 1:
>      print "some greeting"
>      print "type name to search"
>      print "type 'add' to add names or 'quit' to exit"
>      x=raw_input()
>      if x=='quit':
>           break

This looks like the problem:

>      d1={'a name':'1111', 'another name':'2222', 'A. Name':'1111'}

Here the dictionary gets reassigned each time so you're undoing any
modifications.  Try moving this line out of the loop.

>      if x in d1.keys():
>           print d1[x], x
>      if x=='add':
>           add_name()

One other suggestion:  Dictionaries would make managing commands
easier.  For example:

commands = {"add": add_name, "delete": del_name}

Then:

    if x in commands.keys():
        commands[x]()

For quitting it's probably easier to treat that as a special case (as
you have it now), but for everything else it might be useful to do it
this way.

Good luck!

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/