为什么Python不能从游标中正确追加

时间:2014-08-12 03:51:01

标签: python django

我在循环游标时试图理解Python list.append()。 例如,我有一个包含[(itemA,valA),(itemB,valB)]的游标

for item in cursor.fetchall():
    # error doesnt show the correct values
    posts_dict["title"] = item[0]
    posts_dict["description"] = item[1]
    posts_list.append(posts_dict)

- >结果在posts_list中 - > [(itemB,值Valb),(itemB,值Valb)]

但如果我使用列表理解,我会得到正确的值。

for item in cursor.fetchall():
    posts_list.append(dict(title=row[0], description=row[1]))

有人可以解释一下吗?

1 个答案:

答案 0 :(得分:2)

您不断重复使用posts_dict,因此您需要两次添加相同的对象。

for item in cursor.fetchall():
  posts_dict = {}
  posts_dict["title"] = item[0]
  posts_dict["description"] = item[1]
  posts_list.append(posts_dict)

甚至更好:

for item in cursor.fetchall():
  posts_dict = {"title": item[0], "description": item[1]}
  posts_list.append(posts_dict)