将python sql list转换为字典

时间:2015-01-15 19:47:47

标签: python string list 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并在此处找到帮助 ajax json query directly to python generated html gets undefined

5 个答案:

答案 0 :(得分:2)

我可以看到你正在使用format以字符串的形式写。

来自docs

的注释
  

使用str.format()方法

时,无法使用{和}作为填充字符

使外观像字典一样

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

但是如果你想把它变成字典那么你就得做

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

答案 1 :(得分: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]})

答案 2 :(得分: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'}

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

使用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
相关问题