gpt4 book ai didi

python - 将python sql列表转换为字典

转载 作者:太空宇宙 更新时间:2023-11-04 10:29:01 30 4
gpt4 key购买 nike

如何转换

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

结果

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

以以下形式进入字典输出:

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

编辑

这是我目前使用的 fetchone 示例,它工作正常:

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

然后我进行 jQuery 调用并将其传递到 javascript 并在此处找到相关帮助 ajax json query directly to python generated html gets undefined

最佳答案

正如我所看到的,您正在使用 format 以字符串的形式写入。

来自 docs 的注释

it is not possible to use { and } as fill char while using the str.format() method

要让它看起来像一本你可以做的字典

"[{timestamp:'%s',temp:%s}]\n"%(str(row[0]),str(row[1]))

但是如果你想把它变成一个字典那么你将不得不做

row_dic = [{'timestamp':row[0],'temp':row[1]}]

关于python - 将python sql列表转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27971785/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com