Psycopg2: DictCursor vs RealDictCursor

AFAIU and from the docs, RealDictCursor is a specialized DictCursor that allows you to access columns only from keys (aka column name), whereas DictCursor allows you to access data from both keys and index. I was wondering why RealDictCursor was implemented if DictCursor offers more flexibility? Is this so different in performance (or memory) (in favor of the RealDictCursor I imagine ...)?
In other words, what are the use cases for RealDictCursor vs DictCursor?

+4


source to share


2 answers


class psycopg2.extras. RealDictCursor (* args, ** kwargs)

A cursor that uses a real dict as the base type for strings. Note that this cursor is extremely specialized and does not allow normal access (using integer indexes) to retrieve data. If you need to access the string database as both a dictionary and a list, then use a generic DictCursor instead of RealDictCursor. class psycopg2.extras. RealDictConnection The connection that RealDictCursor uses automatically.



Note. Not very useful with Psycopg2.5: you can use psycopg2.connect (dsn, cursor_factory = RealDictCursor ) instead of RealDictConnection . class psycopg2.extras. RealDictRow (cursor) A dict subclass that represents a data record.


+1


source


The main advantage of a real dictionary cursor is the ease of receiving a request as json.

For comparison:

with psycopg2.connect('dbname=test') as connection:
    with connection.cursor(cursor_factory=RealDictCursor) as cursor:
        cursor.execute("select * from my_table")
        print(json.dumps(cursor.fetchall()))

      



against

with psycopg2.connect('dbname=test') as connection:
    with connection.cursor() as cursor:
        cursor.execute("select * from my_table")
        columns = [desc[0] for desc in cursor.description]
        real_dict = [dict(zip(columns, row)) for row in cursor.fetchall()]
        print(json.dumps(real_dict))

      

There is no significant difference between these parameters when it comes to performance.

0


source







All Articles