gpt4 book ai didi

python - 用查询结果填充字典

转载 作者:行者123 更新时间:2023-11-28 20:41:10 24 4
gpt4 key购买 nike

我目前正在这样做:

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

我可以使用一些简写方式来执行此操作,还是应该编写一些辅助函数?

最佳答案

使用 list comprehension :

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

或使用列表理解 zip :

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

如果您使用 Cursor.description attribute ,你可以得到列名:

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

关于python - 用查询结果填充字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34034943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com