python 数据库查询结果转dict_将python sql列表转换为字典

这篇博客展示了如何将Python中的SQLite数据库查询结果转换为字典格式。通过使用`fetchall()`获取所有数据,然后遍历结果,将每行数据的列转化为键值对,存入一个字典列表中,最终得到类似`[{timestamp: '01.15.2015 21:38:52', temp: 21.812}]`的结构。" 133442473,20037631,PHP7下Composer报错:版本兼容性问题及解决方案,"['PHP', 'Composer', '错误处理', '开发工具']
摘要由CSDN通过智能技术生成

How to convert

cursor.execute("SELECT strftime('%m.%d.%Y %H:%M:%S', timestamp, 'localtime'), temp FROM data WHERE timestamp>datetime('now','-1 hours')")

# fetch all or one we'll go for all.

results = cursor.fetchall()

for row in results[:-1]:

row=results[-1]

rowstr="['{0}',{1}]\n".format(str(row[0]),str(row[1]))

temp_chart_table+=rowstr

result

['01.15.2015 21:38:52',21.812]

into dictionary output in form of:

[{timestamp:'01.15.2015 21:38:52',temp:21.812}]

Edit

This is fetchone sample I currenyly use and it works fine:

def get_avg():

conn=sqlite3.connect(dbname)

curs=conn.cursor()

curs.execute("SELECT ROUND(avg(temp), 2.2) FROM data WHERE timestamp>datetime('now','-1 hour') AND timestamp<=datetime('now')")

rowavg=curs.fetchone()

#print rowavg

#rowstrmin=format(str(rowavg[0]))

#return rowstrmin

**d = [{"avg":rowavg[0]}]**

return d

conn.close()

#print get_avg()

schema = {"avg": ("number", "avg")}

data = get_avg()

# Loading it into gviz_api.DataTable

data_table = gviz_api.DataTable(schema)

data_table.LoadData(data)

json = data_table.ToJSon()

#print results

#print "Content-type: application/json\n\n"

print "Content-type: application/json"

print

print json

Then I make jQuery call and pass it into javascript and found help for that in here

ajax json query directly to python generated html gets undefined

解决方案

Try this instead:

cursor.execute("SELECT strftime('%m.%d.%Y %H:%M:%S', timestamp, 'localtime'), temp FROM data WHERE timestamp>datetime('now','-1 hours')")

# fetch all or one we'll go for all.

results = cursor.fetchall()

temp_chart_table = []

for row in results:

temp_chart_table.append({'timestamp': row[0], 'temp': row[1]})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值