用查询结果填充字典

pen*_*ent 3 python mysql-python python-2.7

我目前正在这样做:

    cursor.execute('SELECT thing_id, thing_name FROM things')
    things = [];
    for row in cursor.fetchall():
        things.append(dict([('thing_id',row[0]),
                             ('thing_name',row[1])
                             ]))
Run Code Online (Sandbox Code Playgroud)

我可以使用一些速记来做到这一点,还是应该编写一些辅助函数?

fal*_*tru 5

使用列表理解

things = [{'thing_id': row[0], 'thing_name': row[1]} for row in cursor.fetchall()]
Run Code Online (Sandbox Code Playgroud)

或使用列表理解zip

things = [dict(zip(['thing_id', 'thing_name'], row)) for row in cursor.fetchall()]
Run Code Online (Sandbox Code Playgroud)

如果使用Cursor.descriptionattribute,则可以获得列名:

names = [d.name for d in c.description]
things = [dict(zip(names, row)) for row in cursor.fetchall()]
Run Code Online (Sandbox Code Playgroud)