[Tutor] Re: prepend variable name...
don arnold
darnold02 at sprynet.com
Tue Jan 20 06:54:33 EST 2004
----- Original Message -----
From: "kevin parks" <kp8 at mac.com>
To: "kevin parks" <kp8 at mac.com>
Cc: <tutor at python.org>
Sent: Tuesday, January 20, 2004 1:01 AM
Subject: [Tutor] Re: prepend variable name...
> I should add that, i think the answer lies in making a dictionary (with
> zip?), but what i am not sure of is how to then traverse a dictionary
> in order...
>
Yes, a dictionary is your best option (though zip doesn't enter the picture,
here). In fact, Danny just answered this same question a couple of days ago
with his 'fruitbasket' example. Instead of using a 'regular' variable to
hold your data, you use the variable name as a dictionary key and store your
data there:
myvars = {}
myvars['exI_2a'] = [11,5,7,2]
myvars['exI_2b'] = [0,10,5]
myvars['exI_2c'] = [7,6,9,1]
myvars['exI_2d'] = [4,7,2,7,11]
for key in myvars:
print key
print data
print
[--output--]
exI_2d
[4, 7, 2, 7, 11]
exI_2c
[7, 6, 9, 1]
exI_2b
[0, 10, 5]
exI_2a
[11, 5, 7, 2]
You'll notice that the items aren't necessarily in key order. This is
because a dictionary is an unordered collection. To get around this, you can
use the dicionary's keys() method to generate a list of its keys, then sort
this list before iterating over it.
myvars = {}
myvars['exI_2a'] = [11,5,7,2]
myvars['exI_2b'] = [0,10,5]
myvars['exI_2c'] = [7,6,9,1]
myvars['exI_2d'] = [4,7,2,7,11]
keylist = myvars.keys()
keylist.sort()
for key in keylist:
print key
print myvars[key]
print
[--output--]
exI_2a
[11, 5, 7, 2]
exI_2b
[0, 10, 5]
exI_2c
[7, 6, 9, 1]
exI_2d
[4, 7, 2, 7, 11]
> gosh... dictionaries... hmm... we didn't have those in C so i find that
> i forget how versatile they are. Anyway, i haven't really answered my
> own question yet... but i am i headed in the right direction?
>
> -kp--
Most definitely.
HTH,
Don
More information about the Tutor
mailing list