Remap Mysql tuple to dictionary

Steve Holden steve at holdenweb.com
Tue Sep 26 10:01:34 EDT 2006


Lawrence D'Oliveiro wrote:
> In message <2rTRg.95640$AD5.1277027 at phobos.telenet-ops.be>, Pom wrote:
> 
> 
>>I want to convert a Mysql resulset to a dictionary.
> 
> 
> Here's a function that does this one row at a time:
> 
> def GetEachRecord(TableName, Fields, Condition, Values, Extra = "") :
>     """generator which does an SQL query which can return 0 or more
>     result rows, yielding each record in turn as a mapping from
>     field name to field value. TableName can be a single table name,
>     or a comma-separated list of names for a join. Extra allows
>     specification of order/group clauses."""
>     Cursor = sql.conn.cursor() # modify this as appropriate
>     Cursor.execute \
>       (
>             ", ".join(Fields)
>         +
>             " from "
>         +
>             TableName
>         +
>             " where "
>         +
>             Condition
>         +
>             " "
>         +
>             Extra,
>         Values
>       )
>     while True :
>         NextRow = Cursor.fetchone()
>         if NextRow == None :
>             Cursor.close()
>             raise StopIteration
>         #end if
>         yield dict(zip(Fields, NextRow))
>     #end while
> #end GetEachRecord
> 
> You'd use this something like
> 
>     for Link in GetEachRecord(...) :
>         ... Link[fieldname] ... blah-blah ...
> 
This is a spectacularly bad (non-)solution to the original problem. It 
also shows a fine disregard for readability requirements. I suppose you 
are using a generator to avoid data duplication, but for 100,000 records 
this could be regarded as a premature optimisation on modern computers.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list