从 Postgres 表创建字典列表

问题描述 投票:0回答:1

我想从 postgres 表创建一个字典列表。我使用这个代码:

rows_dict = cur.fetchall() # fetch all rows from the Postgres Database
  
columns = []
entities_list = []
for column in cur.description:
    columns.append(column[0].lower())
entities = {}
for row in rows_dict:
    for i in range(len(row)):
        entities[columns[i]] = row[i]
        if isinstance(row[i], str):
            entities[columns[i]] = row[i].strip()
    print('Output-A:', entities)
    entities_list.append(entities) # add dictionary to the entity_list

print('Output-B:', entities_list) # Here I get a list with x-times the same dictionary... Why?

输出-A 是我在这个缩进级别所期望的(并且这是正确的):多个字典。使用 .append(entities) 我想将这些字典添加到实体列表中。但是,entity_list 在循环中使用 same(=最后!)字典填充多次。我不明白出了什么问题,因为 .append(entities) 与输出 A 的缩进相同。知道那里出了什么问题吗?

python postgresql list dictionary
1个回答
0
投票
rows_dict = cur.fetchall()  # fetch all rows from the Postgres Database
  
columns = []
entities_list = []

# Get column names from cur.description
for column in cur.description:
    columns.append(column[0].lower())

# Iterate through each row and create a new dictionary per row
for row in rows_dict:
    entities = {}  # Create a new dictionary for each row
    for i in range(len(row)):
        entities[columns[i]] = row[i]
        if isinstance(row[i], str):
            entities[columns[i]] = row[i].strip()
    print('Output-A:', entities)
    entities_list.append(entities)  # Add the new dictionary to the entity_list

print('Output-B:', entities_list)  # This will now print the correct list of dictionaries

每次我们在外循环中遍历新行时,

entities
字典都会重置为空字典。这样,就为每一行创建了一个新的字典。

所以在你的代码中

entities = {}
inside循环,所以为每一行创建一个新的字典并将其附加到列表中。

© www.soinside.com 2019 - 2024. All rights reserved.