将SQL数据库中的所有数据以嵌套字典的形式输出
import psycopg2
# establishing the connection
conn = psycopg2.connect(
database="CONNE py",
user='postgres',
password='asdf',
host='localhost',
port= '5432'
)
cursor=conn.cursor()
tables = ["Class_A", "Class_B", "Class_C"]
outer_dict={}
for table in tables:
cursor.execute(f'SELECT name, department, overall_percentage FROM {table}')
rows=cursor.fetchall()
inner_dict={}
for row in rows:
name, department, overall_percentage=row
inner_dict={
'name':name,
'department':department,
'overall_percentage':overall_percentage
}
outer_dict[table]=inner_dict
print(outer_dict)
cursor.close()
这是我现有的代码,在运行这个程序时,对于每个表,我只会得到该表的最后一条数据作为输出。
this is the output:
{'Class_A': {'name': 'Ranga', 'department': 'MCA', 'overall_percentage': 72}, 'Class_B': {'name': 'Delli', 'department': 'MBA', 'overall_percentage': 62}, 'Class_C': {'name': 'Mohan', 'department': 'B.tech AI', 'overall_percentage': 92}}
But i need all the data to be printed like this below ( example output for class A only)
{'Class_A': {{'name': 'Ranga', 'department': 'MCA', 'overall_percentage': 72}, {'name': 'Ranga', 'department': 'MCA', 'overall_percentage': 72}, {'name': 'Ranga', 'department': 'MCA', 'overall_percentage': 72}, }
And I'm new to programming can any one explain me what i did wrong
解决方案
看起来你在每次遍历行时都在覆盖outer_dict[table]。我建议定义一个列表,用来把所有字典追加进去,然后再把它追加到那里。
我建议使用索引作为键:
outer_dict[table] = {}
for i, row in enumerate(rows):
name, department, overall_percentage = row
outer_dict[table][i] = {
'name': name,
'department': department,
'overall_percentage': overall_percentage
}
编辑:我还要指出,你想要的结构在Python中并不有效,集合不能包含字典。照上面的做法,你的输出将会是这样的:
{'Class_A': {0: {...}, 1: {...}, 2: {...}}}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。