将pythonsql列表转换为字典

2024-06-17 12:51:41 发布

您现在位置:Python中文网/ 问答频道 /正文

如何转换

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

结果

^{pr2}$

以以下形式输入词典输出:

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

编辑

这是我目前使用的一个样本,效果很好:

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


Tags: jsondatagetdatetimetabletempcursorresults
3条回答

在大多数python数据库适配器中,可以使用DictCursor来检索记录,该接口类似于python字典,而不是元组。在

使用psycopg2

>>> dict_cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
>>> dict_cur.execute("INSERT INTO test (num, data) VALUES(%s, %s)",
...                  (100, "abc'def"))
>>> dict_cur.execute("SELECT * FROM test")
>>> rec = dict_cur.fetchone()
>>> rec['id']
1
>>> rec['num']
100
>>> rec['data']
"abc'def"

使用MySQLdb

^{pr2}$

如我所见,您正在使用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]))

但如果你想把它写成词典,那你就得这么做了

^{pr2}$

试试这个:

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

相关问题 更多 >