将python sql list转换成字典

最后发布: 2015-01-15 19:47:46


问题

如何转换

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查询中直接找到了针对python生成的html的未定义的帮助

python string list dictionary
回答

如我所见,您正在使用format以字符串形式编写。

来自文档的注释

使用str.format()方法时,不能将{和}用作填充字符

要使其看起来像字典,您可以执行

"[{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'}


回答

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

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


回答

使用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