[Tutor] need a hint

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Mon Dec 2 12:03:56 CET 2013


Oscar Benjamin <oscar.j.benjamin <at> gmail.com> writes:

> 
> On 2 December 2013 02:25, Byron Ruffin <byron.ruffin <at> g.austincc.edu>
wrote:
> >
> > The following program works and does what I want except for one last problem
> > I need to handle.   The program reads a txt file of senators and their
> > associated states and when I input the last name it gives me their state.
> > The problem is "Udall".  There are two of them.  The txt file is read by
> > line and put into a dictionary with the names split.  I need a process to
> > handle duplicate names.  Preferably one that will always work even if the
> > txt file was changed/updated.  I don't want the process to handle the name
> > "Udall" specifically.   For a duplicate name I would like to tell the user
> > it is not a unique last name and then tell them to enter first name and then
> > return the state of that senator.
> 
> You're currently doing this:
> 
> >     senateInfo = {}
> >         senateInfo[lastName] = state
> 
> Instead of storing just a state in the dict you could store a list of
> states e.g.:
> 
>     senateInfo[lastName] = [state]
> 
> Then when you find a lastName that is already in the dict you can do:
> 
>     senateInfo[lastName].append(state)
> 
> to append the new state to the existing list of states. You'll need a
> way to test if a particular lastName is already in the dict e.g.:
> 
>     if lastName in senateInfo:
> 
> Oscar
>

... and since you want to be able to resolve ambiguous last names based on
first names, you will have to store not just the states, but also the first
names.
You can do so by turning the entries in senateInfo from a list of strings
(states) into a list of tuples (first name, state) like this:

    senateInfo[lastName] = [(firstName, state)]

or for pre-existing entries:

    senateInfo[lastName].append((firstName, state))

Best,
Wolfgang




More information about the Tutor mailing list