用查询结果填充字典

3

我目前正在做这件事:

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

有没有一些简便的方法可以做到这一点,还是我应该编写一个小助手函数?
2个回答

5

使用列表推导式

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 属性,你可以获取列名:
names = [d.name for d in c.description]
things = [dict(zip(names, row)) for row in cursor.fetchall()]

太好了,谢谢。我选择了你的第二个代码块,并在我的select语句中明确指定了列名。 - penitent_tangent
@Drewdin,你指的是哪个“dict”? - falsetru
@falsetru 我只想得到字典 things = {'stuff':1},而不是它被包含在列表中 things = [{'stuff':1}]。我猜这是因为使用了列表推导式?谢谢。 - Drewdin

3

您可以通过将游标类传递给 cursor 方法,使用 MySQLdb.cursors.DictCursor 类代替 MySQLdb.cursors.Cursor 类:

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'})

有趣的方法 - 謝謝! - penitent_tangent
我尝试过这个,但每次都会出现“ImportError: No module named mysqldb”的错误。我的系统是Debian Stretch。我已经安装了“sudo apt-get install python-mysqldb”,但是尝试安装时出现了错误:“sh: 1: mysql_config: not found Traceback (most recent call last): …” - RDK
你试过这个了吗?https://dev59.com/Qms05IYBdhLWcg3wD9wB - awesoon
仍在苦苦挣扎。我已经按照评论/答案进行了操作或重复了它们。我的程序在"import mysqldb"行上抛出错误。除此之外,代码运行良好,我只是想尝试您的DictCursor想法。 - RDK
说得太早了。代码可以运行,但我无法从fetchall方法中获取字典对象。 - RDK
我认为最好提出另一个问题,没有实际代码很难说出问题所在。 - awesoon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接