Function to convert fetchone() result from a list to a dictionary
Alex Martelli
aleax at aleax.it
Tue Apr 29 05:09:23 EDT 2003
<posted & mailed>
Carsten Gehling wrote:
> I'm fairly new to Python, and have yet to discover alle the little
> details, that may make my programs look leaner and perhaps become
> faster...
>
> Using the DB API to access databases, I've stumbled upon what I would
> call a shortcoming in the API (IMHO). All the fetch commands return
> the results as lists instead of dictionaries.
Yes. I think what you REALLY want (even though you have no way to
know you want it:-) is Greg Stein's wonderful dtuple.py, see:
http://www.lyra.org/greg/python/dtuple.py
The best explanation and set of examples I know for this is in Steve
Holden's "Python Web Programming" (New Riders) -- I highly recommend
this to Python newbies (even ones not interested in the web per se:
it's got lot of interesting coverage of database issues, too!), and
if you can't purchase it I think you can at least get its examples
free off the web (start looking at Steve's site, www.holdenweb.com).
When you wrap the result of fetchone into a dtuple.DatabaseTuple,
you can then access it in many ways, including dict-like, and the
performance is pretty good too.
Anyway, back to your specific question:
> So I've made my own conversion function, using the cursor.description
> attribute. It's pretty straight-forward, so I was wondering, if
> there's a smarter way to do this?
>
> The function is like this:
> -------------------------------
> def cursor_fetchone_dict(cursor):
> result = cursor.fetchone()
> if result == None: return None
> result_dict = {}
> for i in range(len(result)):
> result_dict[cursor.description[i][0]] = result[i]
> return result_dict
Pretty good (except that you're using tabs, which don't show up
when I reply with KDE 3's KNode:-) You can do a bit better (for
some definition of that term:-) by calling the dict type directly
with a list of key-value tuple -- you can get that from zipping
up a list of keys and a list of values. The list of values you
already have (it's "result"); the list of keys you can get from
the cursor.description with a list comprehension.
So here's a step-by-step version (using SPACES, not TABS:-)...:
def cfd(cursor):
values = cursor,fetchone()
if values is None:
return None
keys = [d[0] for d in cursor.description]
result_dict = dict(zip(keys, values))
return result_dict
Of course, you can bunch this up more, or less, according to
taste -- whatever you find clearest and most readable. E.g.,
the last three lines could be instead:
return dict(zip([d[0] for d in cursor.description],values))
if you're into one-liners!-)
Alex
More information about the Python-list
mailing list