Python MySQLdb:如何获取一个sql选择有一个组的结果到一个字典?

时间:2014-05-28 13:32:28

标签: python mysql mysql-python

我在python中运行了这样的SQL查询:

select sum(a), date from table group by date

然后我执行此查询并获得结果:

    cursor.execute (query, queryParameters)
    rows = cursor.fetchall();

正如预期的行是一个数组:

    (('2014-05-13', Decimal('1.6666666667')), ('2014-05-14', Decimal('33.0151515152')), ('2014-05-15', Decimal('66.4850000000')), ('2014-05-16', Decimal('49.8274022154')), ('2014-05-18', Decimal('4.0000000000')))

但我希望它作为哈希,其中日期是关键,而和是值(每一行都是一个键值对)。由于它是按日期分组,因此将它放入哈希值是有意义的。像这样:

{ '2014-05-13' => '1.6666666667', '2014-05-14' => '33.0151515152'....}

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

更改字段的顺序,并将fetchall()结果传递给dict()

query = "select date, sum(a) from table group by date"
cursor.execute (query, queryParameters)
result = dict(cursor.fetchall())

演示:

>>> from decimal import Decimal
>>> data = (('2014-05-13', Decimal('1.6666666667')), ('2014-05-14', Decimal('33.0151515152')), ('2014-05-15', Decimal('66.4850000000')),
>>> dict(data)
{'2014-05-18': Decimal('4.0000000000'), '2014-05-13': Decimal('1.6666666667'), '2014-05-15': Decimal('66.4850000000'), '2014-05-14': Decimal('33.0151515152'), '2014-05-16': Decimal('49.8274022154')}