【问题标题】:convert python sql list into dictionary将python sql列表转换为字典
【发布时间】: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 query directly to python generated html gets undefined

【问题讨论】:

  • 那个结果好像不对,不应该是[['01.15.2015 21:38:52',21.812]](双[,意思是列表列表)

标签: python string list dictionary


【解决方案1】:

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

来自docs的注释

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

为了使它看起来像一本字典,你可以这样做

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

但如果你想让它成为一本字典,那么你将不得不这样做

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

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

    • 这让我回到了 [{'timestamp': u'01.15.2015 22:06:15', 'temp': 21.875}] 而不是 [{timestamp: '01.15. 2015 22:06:15',温度:21.875}]
    • 在 Python 中,键必须是字符串:'timestamp' 和 'temp'。带有“u”前缀的时间戳值表示该值是一个 Unicode 字符串。这一切都很好。
    • 你是对的!它几乎可以工作,json 格式还可以,现在我在 javascript 级别收到错误,说我的时间戳不能被刺痛 :( 我不知道怎么回事,如果我跳过 json 也没关系。我讨厌时间转换。“错误类型 <type 'unicode '> 当预期日期”。它想从我这里得到什么......回答了最初的问题。谢谢:)
    【解决方案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:

    >>> 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 有一个类似的类:MySQLdb.cursors.DictCursor,您可以将其用作:conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)——或者我想您可以传递游标类(使用相同的关键字参数到连接构造函数)。
    【解决方案4】:
    def stuffToDict(stuff):
        return {"timestamp":stuff[0],"temp":stuff[1]}
    

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

    【讨论】:

    • 我正在尝试从结果中获取正确的格式,以将其放入 Google gviz api 中,以进行可视化。
    • 这很可能是 JSON,如果你 str() 它,这是我的函数返回的内容。
    【解决方案5】:

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

    【讨论】:

      猜你喜欢
      • 2015-07-23
      • 1970-01-01
      • 2015-11-14
      • 2016-10-25
      • 2022-12-04
      • 2011-11-18
      • 2022-08-16
      • 2019-02-10
      • 1970-01-01
      相关资源
      最近更新 更多