用查询结果填充字典 [英] Populate a dictionary with the result of a query

查看:72
本文介绍了用查询结果填充字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在这样做:

    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])
                             ]))

是否可以使用一些速记来完成此操作,还是应该编写一些辅助函数?

Is there some shorthand I can use to do this, or should I write a little helper function?

推荐答案

使用列表理解:

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

或对 zip 使用列表理解:

or using list comprehension with zip:

things = [dict(zip(['thing_id', 'thing_name'], row)) for row in cursor.fetchall()]

如果使用 Cursor.description属性,则可以获得列名称:

If you use Cursor.description attribute, you can get column names:

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

这篇关于用查询结果填充字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆