如何将数据库中的数据转换为python中的表?

时间:2014-07-01 16:00:06

标签: python sql

我从data = cursor.fetchall()的数据库中获取数据,使用

查看数据如下

for row in data: print row

(1644903L, datetime.date(2014, 6, 30), 720994L, 0L, 0L)
(1644976L, datetime.date(2014, 6, 30), 0L, 0L, 0L)
(1645045L, datetime.date(2014, 6, 30), 8600L, 0L, 0L)

它是5列,它们是

id int (10)
date date
revenue1 bigint(10)
revenue2 bigint(10)
revenue3 bigint(10)

我想将data转换为列名为id,date,r1,r2,r3的表。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

这取决于你对表的意思。你的意思是一堆词典?如果是的话

elements = []
for row in data:
    element = {}
    element["id"] = row[0]
    element["date"] = row[1]
    element["r1"] = row[2]
    element["r2"] = row[3]
    element["r3"] = row[4]
    elements.append(element)

然后,您可以通过元素[0] [" id"]等访问元素。或者,如果推荐的访问方法是更多元素[" id"] [0],那么......

elements = {}
elements["id"] = [x[0] for x in data]
elements["date"] = [x[1] for x in data]
elements["r1"] = [x[2] for x in data]
elements["r2"] = [x[3] for x in data]
elements["r3"] = [x[4] for x in data]