You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从PostgreSQL表生成字典列表时出现重复字典的问题求助

PostgreSQL查询结果生成字典列表时重复最后一项的问题

问题原因

你之所以会得到全是最后一个字典的列表,核心原因是字典是可变对象:
你在循环外部只初始化了一次entities = {},后续每轮循环只是修改这个字典里的键值对,而entities_list.append(entities)添加的是这个字典的引用,不是新的副本。列表里的所有元素其实都指向同一个字典对象,最终自然都会显示最后一轮循环修改后的结果。

至于Output-A看起来正常,是因为每次循环打印时,这个字典刚好被更新为当前行的内容,但列表里存的始终是同一个引用。

解决方法

把字典的初始化放到for row in rows_dict:循环内部,每轮循环都创建一个新的字典,这样每次添加到列表里的都是独立的新对象:

rows_dict = cur.fetchall() # fetch all rows from the Postgres Database
  
columns = []
entities_list = []
for column in cur.description:
    columns.append(column[0].lower())

# 将字典创建移至循环内部,每次迭代生成新字典
for row in rows_dict:
    entities = {}
    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)

print('Output-B:', entities_list)

代码优化(可选)

可以用zip函数简化索引循环,让代码更易读:

rows_dict = cur.fetchall()
columns = [col[0].lower() for col in cur.description]
entities_list = []

for row in rows_dict:
    entity = {}
    for col, val in zip(columns, row):
        entity[col] = val.strip() if isinstance(val, str) else val
    entities_list.append(entity)

甚至可以用字典推导式进一步简化成一行:

rows_dict = cur.fetchall()
columns = [col[0].lower() for col in cur.description]
entities_list = [
    {col: val.strip() if isinstance(val, str) else val for col, val in zip(columns, row)}
    for row in rows_dict
]

内容的提问来源于stack exchange,提问作者GIStrees

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 01:20:06