[Tutor] tables and dictionaries

Sheila King sheila@thinkspot.net
Fri, 04 May 2001 22:48:35 -0700


On Sat, 05 May 2001 00:25:15 -0500, "Julieta Rangel"
<julieta_rangel@hotmail.com>  wrote about [Tutor] tables and dictionaries:

:I need to find a way so 
:that once the user enters the set, the computer pairs the elements together 
:as I did above, asks for the required input and stores it in a dictionary. 
:Can this be done?  If so, how?

Yes, this can be done.

if you have the following objects already defined...

list = [e,a,b,ab]
table = {}

(Note: e, a, b, and ab have to already be objects. It might be easiest to let
them be strings and define them as e = 'e' and so forth...)

I suggest a nested loop structure, like this...

for firstElt in list:
    for secondElt in list:
        table[ (firstElt, secondElt) ] = None

What the above code does is, select an element in list. For example, e. Then,
holding 'e' constant as the first Element (the first "for" loop), it goes into
a second for loop on the second Element. So, while "e" is held fixed as the
first element, it will go through the list for the second element, and create
the following tuples:
(e, e)
(e, a)
(e, b)
(e, ab)

After it has done that, it will switch to another element in  the list for the
firstElement. Possibly 'a'. It will hold 'a' fixed on the first for-loop and
on the second for loop, go through all the elements in the list to get the
second element, getting these tuples:
(a, e)
(a, a)
(a, b)
(a, ab)

and so on. The first for-loop will also go through b and ab as the first
element.

The statement

table[ firstElt, secondElt ] = None

puts a key in the dictionary "table", that is a tuple (like one of the example
tuples listed above), and assigns it the value "None", which is a special
value in Python, meaning "no value". I think this is the best value you can
assign in the dictionary "table", while you are generating the ordered pairs,
since you plan on asking the user to input the values for the table later.


--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/