[Tutor] newbie with some basic questions

Paul Sidorsky paulsid@shaw.ca
Mon, 29 Apr 2002 12:21:32 -0600


freddie wrote:

> 2.how can i make input take only one character and not requrie a CR?

Unfortunately this is not an easy thing to do and the solution is
generally platform-specific.  See the Python FAQ at python.org for
ideas.

> 3.i have a simple list of lists for example: people =
> [["A","john","12345"],["B","joe","1231234"],["X","sally","1234"]]
> and i need to do something like:
> some_variable = X
> new_variable = people[*][0]
> that is, find the corresponding list with the list that has [0] = X
> 
> i could use a dictionary like {"X":["sally","1234"]} but is there a
> better way to do it?

If the single character is going to be the only search criteria, then
using a dictionary is definitely "right" here.  It's not only easier but
faster too.

If you may need to search by other fields (e.g. the name field in your
example) then you have a few options.  One is to build two dictionaries
like this:

chardict = {"A": ["A","john","12345"], "B": ["B","joe","1231234"], "X":
["X","sally","1234"]}
namedict = {"john": ["A","john","12345"], "joe": ["B","joe","1231234"],
"sally": ["X","sally","1234"]}

If you put the inner lists in variables first and put those variables in
the dictionaries then it'll cut down on the memory this uses (basically
it'll just be the data in the lists, the keys for both dictionaries, and
a small amount of overhead for references).  Note that if the
dictionaries will be modified then you have to keep the cross-references
updated which slows down insertions and deletions, but the searching
will be very fast.

Another option if search speed isn't a concern is to "unzip" the single
list of lists into three different lists, like this:

chars = ["A", "B", "X"]
names = ["john", "joe", "sally"]
nums = ["12345", "1231234", "1234"]

Then use Python's list object methods, in this case index(), to find
your answer:

idx = chars.index("X")  # Find index of first occurrence of "X".
nameofx = names[idx]    # Get the associated name.

BTW I called this "unzip" because you can use zip(chars, names, nums)
method to build your original single list of lists if you need to, if
you're using Python 2.0 or higher.

I would almost always go for the double-dictionary method (or some
variation thereof) if I couldn't use just a single dictionary, but there
are situations where the multiple-list methods can be better - namely if
insertion/deletion is going to be done much more frequently than
searching.  

Dictionaries are very handy so they would be very much worth learning. 
Besides, knowing the tutor crowd somewhat as I do now, I expect any
other suggestions you get are also going to be dictionary-based.  :-)

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