Probably somewhat silly newbie question
James Stroud
jstroud at mbi.ucla.edu
Mon Feb 26 21:57:14 EST 2007
elgrandchignon at gmail.com wrote:
> Hi all--
>
> Trying to learn Python w/little more than hobbyist (bordering on pro/
> am, I guess) Perl as a background.
>
> My problem is, I have a list of departments, in this instance, things
> like "Cheese", "Bakery", et al. (I work @ a co-op health food store).
> I've populated a list, 'depts', w/these, so that their indexes match
> our internal indexing (which skips a few #'s).
>
> Now, I'd like to simply generate-- and be able to refer to-- a bunch
> of other lists-sets (for subdepartments) by iterating through this
> list, and naming each of these subdepartment lists "categoryx", where
> x is the index # from the master 'depts' list. And then be able to
> populate & refer to these lists by accessing their variable-including
> name.
>
> In Perl, it's a fairly trivial matter to use a string variable in
> naming some other kind of variable-- not sure about Python though. My
> initial, very weak stab at it (don't laugh!) went something like this:
>
> for i in range(len(depts)):
> if depts[i]:
> categorylistdeptname = 'category' + str(i)
> categorylistdeptname = []
>
> Not sure what that wound up doing, but it sure didn't seem to work.
First, your are rebinding categorylistdeptname in the loop every time.
But you probably want a dict (in python 2.4 or later):
deptdict = dict((dept, []) for dept in depts))
And this gets what you want, believe it or not.
Now you can populate each list:
deptdict['Bakery'].append("Donuts")
deptdict['Bulk'].extend(["Granola", "Rasins"])
And work witht the lists by name:
for item in deptdict['Bulk']:
print item
# prints "Granola", "Rasins", etc.
James
More information about the Python-list
mailing list