Fastest way to convert sql result into a dict or list ?

alex23 wuwei23 at gmail.com
Wed Oct 29 15:55:33 CET 2008


On Oct 29, 9:35 pm, "rewo... at gmail.com" <rewo... at gmail.com> wrote:
> I'm trying to find the fastest way to convert an sql result into a
> dict or list.

    >>> from collections import defaultdict
    >>> results = defaultdict(defaultdict)
    >>> for contact_id, field_id, field_name, value in sql_result:
    ...     results[contact_id][field_id] = value
    ...     results[contact_id][field_name] = value
    ...

This lets you reference things in a straightforward way:

    >>> results[1]['email']
    'someth... at something.net'

If you'd prefer to use only the ids for reference:

    >>> results = defaultdict(defaultdict)
    >>> for contact_id, field_id, field_name, value in sql_result:
    ...     results[contact_id][field_id] = (field_name, value)
    ...
    >>> results[1][1]
    ('address', 'something street')

Hope this helps.



More information about the Python-list mailing list