Python psycopg2.extras.DictCursor未在postgres中返回dict
Im使用psycopg2通过以下查询访问postgres数据库。为了从执行的查询返回字典,我在游标中使用DictCursor,但我的输出仍然是一个列表,而不是一个DictCursor 下面是程序和输出Python psycopg2.extras.DictCursor未在postgres中返回dict,python,postgresql,psycopg2,Python,Postgresql,Psycopg2,Im使用psycopg2通过以下查询访问postgres数据库。为了从执行的查询返回字典,我在游标中使用DictCursor,但我的输出仍然是一个列表,而不是一个DictCursor 下面是程序和输出 import psycopg2.extras try: conn = psycopg2.connect("user='postgres' host='localhost' password='postgres'", ) except
import psycopg2.extras
try:
conn = psycopg2.connect("user='postgres' host='localhost' password='postgres'",
)
except:
print "I am unable to connect to the database"
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute("""SELECT datname from pg_database""")
rows = cur.fetchall()
print "\nShow me the databases:\n"
print rows
输出:-
[['template1'], ['template0'], ['postgres'], ['iip'], ['test'], ['test_postgres'], ['testdb']]
它看起来像一个列表,闻起来像一个列表,但它是一个
直接继承内置的
列表
,并添加实现字典逻辑所需的所有方法,但它不会更改表示形式\uuuuuu repr\uuuuu
或\uu str\uuuu
,因此输出与列表相同
fetchall()
将所有查询的行打包到一个列表中,而不指定确切的类型
顺便说一句,也许你正在寻找这种游标:?对于那些因为喜欢方便地引用字典中的列:值记录表示法而来的人来说,PRMoureu的答案是,具有所有常用的字典逻辑,这意味着你可以使用.items()在DictRow上进行迭代并获取键:值对
rows = cur.fetchall()
row_dict = [{k:v for k, v in record.items()} for record in rows]
将您的DictRow记录列表转换为dict记录列表 AFAICT
row_dict=[{k:record[k]for k in record}for record in rows]
将不起作用。太好了,谢谢!
rows = cur.fetchall()
print([row['datname'] for row in rows])
class DictRow(list):
"""A row object that allow by-column-name access to data."""
rows = cur.fetchall()
row_dict = [{k:v for k, v in record.items()} for record in rows]