将 python sql 列表转换成字典

convert python sql list into dictionary

如何转换

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 并在此处找到相关帮助

def stuffToDict(stuff):
    return {"timestamp":stuff[0],"temp":stuff[1]}

那将是一本字典。您显示的示例输出是一个字典列表,可以通过在字典周围放置方括号来实现。不过,我不知道你为什么想要那个。此外,由于缺少引号,python 语法不合法。

据我所知,您正在使用 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]}]

试试这个:

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

在大多数 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:

>>> import MySQLdb 
>>> import MySQLdb.cursors 
>>> myDb = MySQLdb.connect(user='andy47', passwd='password', db='db_name', cursorclass=MySQLdb.cursors.DictCursor) 
>>> myCurs = myDb.cursor() 
>>> myCurs.execute("SELECT columna, columnb FROM tablea") 
>>> firstRow = myCurs.fetchone() 
{'columna':'first value', 'columnb':'second value'}

使用 MySQLdb 的游标库。

import MySQLdb
import MySQLdb.cursors

conn = MySQLdb.connect(host=db_host, user=db_user, passwd=db_passwd, db=db_schema, port=db_port, cursorclass=MySQLdb.cursors.DictCursor)

cursor = conn.cursor()

cursor.execute("SELECT timestamp, localtime, temp FROM data WHERE timestamp>datetime('now','-1 hours')")
# fetch all or one we'll go for all.
results = cursor.fetchall()

然后您可以访问字典形式的结果:

>>> results['timestamp']
14146587
>>> results['localtime']
20:08:07
>>> results['temp']
temp_variable_whatever