Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: Best way to enumerate something in python

Reply
Thread Tools

Re: Best way to enumerate something in python

 
 
David Stockwell
Guest
Posts: n/a
 
      05-26-2004
Thanks for the help.

I found out range creates lists not tuples, so apparently they can get
changed (for an enum type approach).

I'm going to use them in SQL statements that get generated on the fly. I
need to be able to refer to a particular column in a meaningful way which
is why if i had an enumerated type it might be easy to do so.

i did some reading and if i interpreted this correctly, dictionaries are
hashed, correct? If so i might be able to get away with referencing the
dictionary and passing the hashkey in this case a number to retrieve the
column name. However, I'd like to do this mnemonically so I can refer to
the column name with a short cut name that makes sense instead of saying
something like

insrtCommand = ' select ' + columns[1] + ',' + columns[2] + ' from '
blah.......

from a maintenance standpoint, the programmer can't tell what column 1 is
supposed to refer to. however if i had something like

columns[HOUSING_ID] instead of the '1' then the programmer would later at
a glance be able to follow the code.




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




>From: "Larry Bates" <(E-Mail Removed)>
>To: http://www.velocityreviews.com/forums/(E-Mail Removed)
>Subject: Re: Best way to enumerate something in python
>Date: Wed, 26 May 2004 08:54:10 -0500
>
>David,
>
>You may have to give us more detail about what
>you want to do, but here goes:
>
>listofcolumns=('field1','field2','field3')
>for column in listofcolumns:
> <do something>
>
>Most of the time I find that putting the names
>in a dictionary with the column name as key and
>offset as the value seems to work better.
>
>dictofcolumns={'field1':1, 'field2': 2, 'field3':3}
>
>value_for_field3=row[dictofcolumns['field3']]
>
>For your second question I think you should
>take a look at os.path.getatime, .gmtime, getsize
>they are easier to use.
>
>Larry Bates
>Syscon, Inc.
>
>
>"David Stockwell" <(E-Mail Removed)> wrote in message
>news:(E-Mail Removed)...
> > Hi Everyone,
> >
> > I'm wondering about the best way to enumerate something.
> >
> > I have a list of columnames for a db and I decided to put them in a

>giant
> > tuple list for two reasons:
> > 1) its unchangeable
> > 2) I was hoping that creating an enumeration of those names would be

>easy
> >
> > In the os.stat there is aparrently a list of things you can refer to eg:
> > ST_SIZE, ST_ATIME, etc.
> >
> > How are these defined? They appear to be related to 0,1,2,3,.... some
> > sort of enumeration.
> >
> > I would like to create an enumeration with 'friendly names' that map to

>the
> > particular offset in my column name tuple.
> >
> > Thanks,
> >
> >
> >
> > David
> > -------
> > tracfone: http://cellphone.duneram.com/index.html
> > Cam: http://www.duneram.com/cam/index.html
> > Tax: http://www.duneram.com/index.html
> >
> > __________________________________________________ _______________
> > FREE pop-up blocking with the new MSN Toolbar get it now!
> > http://toolbar.msn.click-url.com/go/...ave/direct/01/
> >
> >

>
>
>--
>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/...ave/direct/01/


 
Reply With Quote
 
 
 
 
tutu
Guest
Posts: n/a
 
      05-27-2004
>
> insrtCommand = ' select ' + columns[1] + ',' + columns[2] + ' from '
> blah.......
>
> from a maintenance standpoint, the programmer can't tell what column 1 is
> supposed to refer to. however if i had something like
>
> columns[HOUSING_ID] instead of the '1' then the programmer would later at
> a glance be able to follow the code.
>

I've been using something like the following (maybe it helps):
import types

class Field(object):
"a field has a name , a value and an index in a row from a rowset"
def __init__(self, name, value, idx):
self.name =name
self.value=value
self.index=idx
def __repr__(self): return self.name

class Fields(object):
def __init__(self, fields_dict):
self._fields = fields_dict
self.fieldsCount = len(self._fields.keys())
self.row = None

def _setFields(self):
self._fldName = {}
self._fldIdx = {}
for nm, idx in self._fields.items():
self._fldName[nm] = self._fldIdx[idx] = Field(nm,
self._row is not None and self._row[idx] or None, idx)

def __getitem__(self, fld):
if type(fld) in [types.IntType, types.LongType]:
if 0<=fld<=self.fieldsCount-1: return self._fldIdx[fld]
raise IndexError, "Index out of bounds %d" % fld
elif type(fld) in [types.StringType, types.UnicodeType]:
if self._fldName.has_key(fld):
return self._fldName[fld]
raise ValueError, "No such field %s" % idx
else:
raise ValueError, "key may only be a text (field_name) or
a number (field index in row)"

def setRow(self, rowLst):
self._row = rowLst
self._setFields()

row = property(fget= lambda self: self._row, fset = setRow)


fields = Fields(dict(name=0, phone=1, address=2))
sql = "select %s, %s, %s from addressbook" %
(fields[0],fields[1],fields[2])
print sql
sql = "select %s from addressbook" % ",
".join((str(fields['name']),str(fields['phone']))) #needs str()
because type(fields['name'])==Field not str
print sql
sql = "select %s, %s from addressbook" % (fields['name'].name,
fields['phone'].name)
print sql
#r = cursor.execute(sql)
#rows = r.fetchall()
rows=(("jon","ext 391","jon address"),("bob","ext 294", "bob
address"))
for row in rows:
fields.row=row
print "by field name: name=%s\taddress=%s\tphone=%s" %
(fields['name'].value, fields['address'].value, fields['phone'].value)
print "by field index: name=%s\taddress=%s\tphone=%s" %
(fields[0].value, fields[2].value, fields[1].value)
print

=>
select name, phone, address from addressbook
select name, phone from addressbook
select name, phone from addressbook
by field name: name=jon address=jon address phone=ext 391
by field index: name=jon address=jon address phone=ext 391

by field name: name=bob address=bob address phone=ext 294
by field index: name=bob address=bob address phone=ext 294

Good Look
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Best way to enumerate classes in a module Дамјан Георгиевски Python 5 06-26-2009 09:56 AM
Re: Best way to enumerate something in python David Stockwell Python 3 05-27-2004 05:31 PM
Best way to enumerate something in python David Stockwell Python 2 05-26-2004 05:40 PM
re best way to enumerate something in Python David Stockwell Python 2 05-26-2004 05:18 PM
ruby way to enumerate users Robert K. Ruby 9 02-02-2004 04:17 PM



Advertisments