python - 使用 python 作为字典从 postgresql 查询

标签 python postgresql python-2.7 dictionary psycopg2

我正在使用 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/

相关文章:

python - 如何使用 paramiko 通过键盘身份验证

postgresql - 使用 psycopg2 在不执行查询的情况下获取 PostgreSQL 结果集列类型

python - 如何在 Python 中检查另一个字典中是否存在值的键(如一个字典中所定义)?

Python 日志记录。将格式化程序与 logging.exception() 一起使用

sql - 如何使用 PostgreSQL 触发器来存储更改(SQL 语句和行更改)

python - 将网络拆分为多个前缀的子网

python - 如何使用 QGraphicsScene 和 QGraphicsView 在 PyQt 中分层图像

python - 使用 Django 服务 Keras 模型

python - pubDate RSS 使用 Beautifulsoup/Python 解析怪异

sql - postgresql:更新最新插入行的快速方法