用查询结果填充字典

2024-05-21 05:33:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在正在做:

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

有什么速记法可以用来做这个,或者我应该写一个小的助手函数吗?


Tags: nameinfromidforexecuteselectcursor
2条回答

使用list comprehension

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

或者将列表理解与^{}一起使用:

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

如果使用^{} attribute,则可以获取列名:

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

通过将游标类传递给^{}方法,可以使用^{}类而不是^{}

In [9]: cur = conn.cursor(MySQLdb.cursors.DictCursor)

In [10]: cur.execute('SELECT * FROM test_table')
Out[10]: 3L

In [11]: cur.fetchall()
Out[11]: 
({'create_time': datetime.datetime(2015, 12, 2, 10, 22, 23),
  'id': 1L,
  'name': 'Bob'},
 {'create_time': datetime.datetime(2015, 12, 2, 10, 22, 34),
  'id': 2L,
  'name': 'Stive'},
 {'create_time': datetime.datetime(2015, 12, 2, 10, 22, 37),
  'id': 3L,
  'name': 'Alex'})

相关问题 更多 >