SV: Function to convert fetchone() result from a list to a dictionary
Carsten Gehling
carsten at gehling.dk
Tue Apr 29 07:43:32 EDT 2003
> -----Oprindelig meddelelse-----
> Fra: python-list-admin at python.org
> [mailto:python-list-admin at python.org]Pa vegne af Alex Martelli
> Sendt: 29. april 2003 11:09
> 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
I already have this book, but unfortunately (for me) the chapters about
database manipulation is about the only section of the book, that I haven't
shuffled through. :-)
Looking at dtuple.py I think it may be shooting a bit over target. I could
be wrong - after all, I'm very new to Python :)
> 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).
Will do this!
> 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
Heh - I like using tabs. It makes it easier for me to control indentation.
> 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
Hmm... (looking up zip() in the documentation...). Okay I understand
everyting except this contruct:
keys = [d[0] for d in cursor.description]
Let me guess: it loops through cursor.description (obvious), for each of the
items (which are tuples) it "outputs" element 0. The output is then
automatically formatted in a way, that conforms to the list creation syntax.
Or something like that. Kind of neat - haven't seen that in any other
language, that I've used.
> return dict(zip([d[0] for d in cursor.description],values))
>
> if you're into one-liners!-)
I'm not - I'd like to be able to read my own code 6 months from now... ;-)
- Carsten
BTW: Wish me welcome - I've just subscribed. And the way I continue to be
marveled by Python, I'm not likely to unsibscribe again. :-)
More information about the Python-list
mailing list