dict_cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
dict_cur.execute("SELECT column1, column2, column3 FROM mytable")
result = dict_cur.fetchall()
print result[0]
>>> {'column2':10, 'column1':12, 'column3':42}
How could I preserve column ordering without parsing executed SQL first? It works well with normal cursor when list is returned, but I need access to dictionary keys and therefore need to use RealDictCursor.
EDIT: Well, I actually can't. description attribute of the cursor object should be used for getting column names.
You can use psycopg2.extras.NamedTupleCursor
and then use namedtuple_obj._asdict()
to convert that to an OrderedDict
.
Note: In ordered to get this functionality "out of the box" we need to have Python version >= 2.7.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With