How to get data from redshift table as dictionary in python

Table of Contents
The dict cursors allow to access to the retrieved records using an interface similar to the Python dictionaries instead of the tuples.


Add following code into your cursor function

cursor_factory=psycopg2.extras.RealDictCursor

After adding the above code your cursor should be look like this –

cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)

if you have an error of not found class .extra –
AttributeError: module ‘psycopg2’ has no attribute ‘extras’


Resolved this error by importing class as below

import psycopg2
import psycopg2.extras

Now if you run this code, you will get data in dictionary from redshift  as key, value pair like below :-

{‘id’: 1234567, ‘date’: datetime.date(2019, 2, 13), ‘hour’: 0, ‘code’: 42107, ‘count’: 6, ‘revenue’: None, ‘payout’: None, ‘week’: 7}

Related posts