如何用Python将查询结果转换为字典?
我需要将查询结果转换成字典,当前输出的类型是元组。共有3 个表输出,如何将它们分别以列名作为键,合并成一个字典输出?
我尝试使用zip和 dict来转换,但会报错。
import psycopg2
# establishing the connection
conn = psycopg2.connect(
database="CONNETpy",
user='postgres',
password='pass',
host='localhost',
port= '5432'
)
cursor = conn.cursor()
tables = ["Class_A", "Class_B", "Class_C"]
for table in tables:
cursor.execute(f"SELECT * FROM {table}")
results = cursor.fetchall()
c=(f"{table}",results)
dict1=dict(zip(results))
print(dict1)
解决方案
这种方法是最简洁的,因为它在驱动层就完成了映射
import psycopg2
from psycopg2.extras import RealDictCursor
# establishing the connection
conn = psycopg2.connect(
database="CONNETpy",
user='postgres',
password='pass',
host='localhost',
port='5432'
)
# Use RealDictCursor to get results as dictionaries
cursor = conn.cursor(cursor_factory=RealDictCursor)
tables = ["Class_A", "Class_B", "Class_C"]
combined_dict = {}
for table in tables:
cursor.execute(f"SELECT * FROM {table}")
# fetchall() returns a list of RealDict objects
results = cursor.fetchall()
# Store results in the master dict using the table name as the key
combined_dict[table] = [dict(row) for row in results]
print(combined_dict)
cursor.close()
conn.close()
如果你不能改变游标类型,你必须手动把 cursor.description 与每一行配对(与Pravash的回答相同):
combined_dict = {}
for table in tables:
cursor.execute(f"SELECT * FROM {table}")
column_names = [desc[0] for desc in cursor.description]
results = cursor.fetchall()
combined_dict[table] = [dict(zip(column_names, result)) for result in results]
cursor.close()
conn.close()
print(tables_dict)
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。