Best way to enumerate something in python

David Stockwell winexpert at hotmail.com
Thu May 27 11:19:26 EDT 2004


All I can say is

WOW!

It took me a bit to figure out what you were doing but I think I see it.

Let me see if I get this right:
First declare a string with the 'base name' of all my columns in it.
declare my dictionary (for later sql statement grabs) and make it empty.
I think create a list of field names and enter a loop
   in the loop:  create a variable using the basename and append a "_COL" to 
form an easy lookup constant.  and assign that new variable with the loop 
index.
   still in the loop, add a dictionary entry mapping the string to the var 
name

Its pretty impressive....  Guess I still have a lot to learn with python....

David
-------
Cell: http://cellphone.duneram.com/index.html
Cam: http://www.duneram.com/cam/index.html
Tax: http://www.duneram.com/index.html




>From: Peter Hansen <peter at engcorp.com>
>To: python-list at python.org
>Subject: Re: Best way to enumerate something in python
>Date: Thu, 27 May 2004 10:40:05 -0400
>
>David Stockwell wrote:
>
>>FWIW this is what I'm going to do for enumerated types in python.  Its not 
>>perfect but it will make it fairly easy to get at column names so I can 
>>build SQL statements on the fly and still have fairly easy to maintain 
>>code
>>
>>#setup stuff
>>NAME_COL,     ADDRESS_COL,    CITY_COL,  ZIPCODE_COL, \
>>STATE_COL,    COUNTRY_COL,    SS_COL,    CAT_COL, \
>>DATE_COL,     SALARY_COL                              = range(10)
>>
>>mycol = {
>>      NAME_COL: " NAME ",   ADDRESS_COL: " ADDRESS ",
>>      CITY_COL: " CITY ",   ZIPCODE_COL: " ZIPCODE ",
>>      STATE_COL:" STATE ", COUNTRY_COL:  " COUNTRY ",
>>      SS_COL:   " SS ",       CAT_COL:   " CAT ",
>>      DATE_COL: " DATE ",   SALARY_COL:  " SALARY " }
>># Use these for indexing by column name
>
>Any time you see a pattern of repetition like this, you can
>make improvements, at least with Python if not some other
>languages.  If nothing else, this will generally vastly improve
>maintainability, and often readability as well.
>
>
> >>> cols = 'NAME ADDRESS CITY ZIPCODE STATE COUNTRY SS CAT DATE SALARY'
> >>> mycol = {}
> >>> for i,col in enumerate(cols.split()):
>...     globals()[col + '_COL'] = i
>...     mycol[i] = ' %s ' % col
>...
> >>> dir()
>['ADDRESS_COL', 'CAT_COL', 'CITY_COL', 'COUNTRY_COL', 'DATE_COL', 
>'NAME_COL', 'SALARY_COL', 'SS_COL', 'STATE_COL', 'ZIPCODE_COL', 
>'__builtins__', '__doc__', '__name__', 'col', 'cols', 'enum', 'i', 'mycol']
> >>> mycol[CITY_COL]
>' CITY '
>
>-Peter
>--
>http://mail.python.org/mailman/listinfo/python-list

_________________________________________________________________
FREE pop-up blocking with the new MSN Toolbar – get it now! 
http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/





More information about the Python-list mailing list