我正在使用 Python 2.7 和 postgresql 9.1。 试图从查询中获取字典,我尝试了这里描述的代码: http://wiki.postgresql.org/wiki/Using_psycopg2_with_PostgreSQL
import psycopg2
import psycopg2.extras
conn = psycopg2.connect("dbname=mydb host=localhost user=user password=password")
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute ("select * from port")
type(cur.fetchall())
它正在打印下一个答案:
<type 'list'>
打印项目本身,告诉我它是列表。 异常(exception)的答案是字典。
编辑:
尝试下一个:
ans = cur.fetchall()[0]
print ans
print type(ans)
返回
[288, 'T', 51, 1, 1, '192.168.39.188']
<type 'list'>
最佳答案
Tnx 很多 Andrey Shokhin,
完整答案是:
#!/var/bin/python
import psycopg2
import psycopg2.extras
conn = psycopg2.connect("dbname=uniart4_pr host=localhost user=user password=password")
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute ("select * from port")
ans =cur.fetchall()
ans1 = []
for row in ans:
ans1.append(dict(row))
print ans1 #actually it's return
关于python - 使用 python 作为字典从 postgresql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21158033/