Probably somewhat silly newbie question

elgrandchignon at gmail.com elgrandchignon at gmail.com
Mon Feb 26 22:01:02 EST 2007


On Feb 26, 6:57 pm, James Stroud <jstr... at mbi.ucla.edu> wrote:
> elgrandchig... 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

Thanks so much James!  I'll give that method a shot.




More information about the Python-list mailing list