Python 如何将db.query(sql)的结果转换为dict的列表?

Python 如何将db.query(sql)的结果转换为dict的列表?,python,web.py,Python,Web.py,我对Python和web.py(我目前正在使用)都是新手,所以请耐心听我说 在: 看起来查询的结果是一个字典列表{total_user:num},对吗 我的情况非常相似:对数据库运行SELECT,希望得到key:value数据列表 在models.py中: def get_items: return self.db.query("SELECT title FROM news") 在code.py中: items = model.get_items return render.list(

我对Python和web.py(我目前正在使用)都是新手,所以请耐心听我说

在:

看起来查询的结果是一个字典列表{total_user:num},对吗

我的情况非常相似:对数据库运行SELECT,希望得到key:value数据列表

在models.py中:

def get_items:
    return self.db.query("SELECT title FROM news")
在code.py中:

items = model.get_items
return render.list(items)
在templates/list.html中:

$def with (items)
$for item in items:
    <p>$item.title</p>
$def和(项目)
项目中的项目为$:
$item.title

但是,代码会触发一个错误,因为“'tuple'对象没有属性'title'”。
我做错了什么?提前感谢您的帮助。

它会触发,因为您只需从新闻中选择title属性,这显然会产生类似元组(a、b、c、d)的结果。 如果您想要一个对象作为结果,请执行以下操作

self.db.query("SELECT * FROM news")

谢谢Abdul,但实际上我简化了查询以节省空间。在原始查询中,选择了多个字段(包括课程标题),结果仍然相同。需要注意的是,我使用的是MySQLdb。切换到Postgres可消除此问题-结果将正确地作为字典返回。看起来
get\u items
函数定义和调用中有错误。它应该是
def get_items()
items=model.get_items()
self.db.query("SELECT * FROM news")