On Mon, Oct 01, 2007 at 10:12:04AM -0400, Carsten Haese wrote regarding Re: Select as dictionary...: > > On Mon, 2007-10-01 at 09:57 -0400, J. Clifford Dyer wrote: > > > > > 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()) >
This is only an improvement if the SQL query remains a list of 2-tuples. If the OP wants to add more values, the more verbose version allows for easier extensibility. for k,v1,v2 in links: linkdict[k] = (v1, v2) Of course even better would be not to have to add variables, so maybe: for link in links: linkdict[link[0]] = link[1:], which changes the output format somewhat, but keeps the access by dict keyed to the DB id. > 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)) > Agreed. A much better solution. Cheers, Cliff -- http://mail.python.org/mailman/listinfo/python-list