Select as dictionary...

Carsten Haese carsten at uniqsys.com
Mon Oct 1 16:12:04 CEST 2007


On Mon, 2007-10-01 at 09:57 -0400, J. Clifford Dyer wrote:
> On Mon, Oct 01, 2007 at 06:32:07AM -0700, Besturk.Net Admin wrote regarding Select as dictionary...:
> > 
> > aia.execute("SELECT id, w from list")
> > links=aia.fetchall()
> > print links
> > 
> > and result
> > [(1, 5), (2,5).......] (2 million result)
> > 
> > I want to see this result directly as a dictionary:
> > 
> > {1: 5, 2: 5 .....}
> > 
> > How do i select in this format ?
> > 
> Try this:
> 
> aia.execute("SELECT id, w from list")
> links=aia.fetchall()
> linkdict = dict()
> for k,v in links:
>     linkdict[k] = v
> print linkdict

Improvement 1: Use the fact that dict can be initialized from a sequence
of key/value pairs:

aia.execute("SELECT id, w from list")
linkdict = dict(aia.fetchall())

Improvement 2: Use an iterator instead of reading all rows into memory:

aia.execute("SELECT id, w from list")
linkdict = dict(iter(aia.fetchone,None))

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list