MySQLdb and ordering of column names in list returned by keys() w/ a DictCursor

Tim Chase python.list at tim.thechases.com
Thu Jul 2 12:50:09 EDT 2009


> Will this order at least be the same for that same query every time the
> script is executed?

I wouldn't count on it.  The order is only defined for the one 
iteration (result of the keys() call).  If the order matters, I'd 
suggest a double-dispatch with a non-dict (regular/default) query 
result, something like

   header_map = dict(
     (desc[0], i)
     for i,desc in enumerate(cursor.description)
     )
   for row in cursor.fetchall():
     print row[header_map['league']]

If you have a lot of fields, I often use a closure to simplify 
the coding:

   for row in cursor.fetchall():
     item = lambda s: row[headermap[s]]
     print item('league')
     print item('BB')
     print item('player_id')

That way, the row stays in order, if you need it that way:

   league, bb, hr, ip, k, h, id, er = row

-tkc






More information about the Python-list mailing list