Mark Harrison Mark Harrison - 1 year ago 210
Python Question

cx_Oracle: How can I receive each row as a dictionary?

By default, cx_Oracle returns each row as a tuple.

>>> import cx_Oracle
>>> conn=cx_Oracle.connect('scott/tiger')
>>> curs=conn.cursor()
>>> curs.execute("select * from foo");
>>> curs.fetchone()
(33, 'blue')

How can I return each row as a dictionary?

Answer Source

You can override the cursor's rowfactory method. You will need to do this each time you perform the query.

Here's the results of the standard query, a tuple.

curs.execute('select * from foo')
    (33, 'blue')

Returning a dictionary:

def makeNamedTupleFactory(cursor):
    columnNames = [d[0].lower() for d in cursor.description]
    import collections
    Row = collections.namedtuple('Row', columnNames)
    return Row

curs.rowfactory = makeDictFactory(curs)
    {'Y': 'brown', 'X': 1}

Returning a named tuple:

def makeDictFactory(cursor):
    columnNames = [d[0] for d in cursor.description]
    def createRow(*args):
        return dict(zip(columnNames, args))
    return createRow

curs.rowfactory = makeNamedTupleFactory(curs)
    Row(x=33, y='blue')

Credit to Amaury Forgeot d'Arc:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download