Python MySQLdb:如何将带有分组的 SQL 查询结果转换为字典?

3 投票
1 回答
3322 浏览
提问于 2025-04-18 07:49

我在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 个回答

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

撰写回答