【问题标题】:Populate a dictionary with the result of a query用查询结果填充字典
【发布时间】:2016-03-06 05:36:57
【问题描述】:

我目前正在这样做:

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

我可以使用一些速记来做到这一点,或者我应该写一个小辅助函数吗?

【问题讨论】:

    标签: python python-2.7 mysql-python


    【解决方案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()]
    

    【讨论】:

    • 完美,谢谢。我已经使用了您的第二个代码块,并在我的 select 语句中明确表达了列名。
    • @Drewdin,dict 是什么意思?
    • @falsetru 我只想得到 dict,things = {'stuff':1},而不是在列表中。东西 = [{'stuff':1}]。我猜它是必需的,因为它是一个列表理解?谢谢
    【解决方案2】:

    您可以通过将游标类传递给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'})
    

    【讨论】:

    • 有趣的方法 - ta!
    • 我试过这个,但每次我得到“ImportError: No module named mysqldb”。运行德班伸展运动。我安装了“sudo apt-get install python-mysqldb”。试过这个,但安装错误“sh:1:mysql_config:找不到Traceback(最近一次调用最后一次):......”
    • 还在挣扎。我已经按照 cmets/answers 完成或重复了它们。我的程序在“import mysqldb”行抛出错误。除了代码运行良好之外,我只是想试试你的 DictCursor 想法。
    • 说得太早了。代码有效,但我没有从 fetchall 方法中获取字典对象。
    猜你喜欢
    • 2011-10-22
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 2017-12-24
    • 2016-03-12
    • 1970-01-01
    • 2014-05-11
    相关资源
    最近更新 更多