Select as dictionary...

J. Clifford Dyer jcd at sdf.lonestar.org
Mon Oct 1 10:11:56 EDT 2007


On Mon, Oct 01, 2007 at 03:50:59PM +0200, Bruno Desthuilliers wrote regarding Re: Select as dictionary...:
> 
> IIRC, postgres' db-api connector (well, at least one of them - I don't 
> know which one you're using) has a DictCursor. You should find all you 
> want to know in the relevant doc.
> 

Correct me if I'm wrong, but I think the DictCursor would output the following:

[{'id': 1, 'value': 5}, {'id': 2, 'value': 5}, ...]

But the OP wanted one dict with IDs as keys:

{1: 5, 2: 5, ...}

As a side note to the OP, a better format might be:

{1: (5,), 2: (5,), ...}

Where each key keys into a tuple, in case you want to pull more than one value from the DB. Also, in this format, it is essential that the record used as a key be a primary key or uniquely indexed, in order to avoid collisions.  If you intend to make this code reusable, it might be worth explicitly checking for this, and raising an exception if it is not.

Cheers,
Cliff





More information about the Python-list mailing list