Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve column order while using psycopg2.extras.RealDictCursor

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.

like image 257
kerma Avatar asked Feb 10 '12 16:02

kerma


1 Answers

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.

like image 135
Phani Avatar answered Oct 23 '22 09:10

Phani