How to keep column order when 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 can I keep column ordering without parsing SQL? It works well with the normal cursor when the list is returned, but I need access to the dictionary keys, and so you need to use RealDictCursor.

EDIT : Well, I really can't. the cursor object description attribute should be used to get the column names.

+7
source share
2 answers

I don’t have this extras package, but usually the cursor should have a property called description , which is a tuple containing all the columns in order, as well as additional information such as the type of field, etc.

Try " print dict_cur.description " in the python shell and see what you get.

EDIT: it doesn't matter. I did not read your "EDIT" ...

+1
source

You can use psycopg2.extras.NamedTupleCursor and then use namedtuple_obj._asdict() to convert this to OrderedDict .

Note. When ordering this function out of the box, we must have a Python version> = 2.7.

+1
source

All Articles