I’m using Python 2.7 and postgresql 9.1. Trying to get dictionary from query, I’ve tried the code as described here: http://wiki.postgresql.org/wiki/Using_psycopg2_with_PostgreSQL
JavaScript
x
7
1
import psycopg2
2
import psycopg2.extras
3
conn = psycopg2.connect("dbname=mydb host=localhost user=user password=password")
4
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
5
cur.execute ("select * from port")
6
type(cur.fetchall())
7
It is printing the next answer:
JavaScript
1
2
1
<type 'list'>
2
printing the item itself, show me that it is list. The excepted answer was dictionary.
Edit:
Trying the next:
JavaScript
1
4
1
ans = cur.fetchall()[0]
2
print ans
3
print type(ans)
4
returns
JavaScript
1
3
1
[288, 'T', 51, 1, 1, '192.168.39.188']
2
<type 'list'>
3
Advertisement
Answer
If you don’t want to use a psycopg2.extras.DictCursor
you can create a list of dictionaries for the results using cursor.description
:
JavaScript
1
22
22
1
# connect
2
connection = psycopg2.connect()
3
cursor = connection.cursor()
4
5
# query
6
cursor.execute("SELECT * FROM myTable")
7
8
# transform result
9
columns = list(cursor.description)
10
result = cursor.fetchall()
11
12
# make dict
13
results = []
14
for row in result:
15
row_dict = {}
16
for i, col in enumerate(columns):
17
row_dict[col.name] = row[i]
18
results.append(row_dict)
19
20
# display
21
print(result)
22
I use the following function fairly regularly:
JavaScript
1
37
37
1
def select_query_dict(connection, query, data=[]):
2
"""
3
Run generic select query on db, returns a list of dictionaries
4
"""
5
logger.debug('Running query: {}'.format(query))
6
7
# Open a cursor to perform database operations
8
cursor = connection.cursor()
9
logging.debug('Db connection succesful')
10
11
# execute the query
12
try:
13
logger.info('Running query.')
14
if len(data):
15
cursor.execute(query, data)
16
else:
17
cursor.execute(query)
18
columns = list(cursor.description)
19
result = cursor.fetchall()
20
logging.debug('Query executed succesfully')
21
except (Exception, psycopg2.DatabaseError) as e:
22
logging.error(e)
23
cursor.close()
24
exit(1)
25
26
cursor.close()
27
28
# make dict
29
results = []
30
for row in result:
31
row_dict = {}
32
for i, col in enumerate(columns):
33
row_dict[col.name] = row[i]
34
results.append(row_dict)
35
36
return results
37