SQL结果集(python列表)到字典

2024-10-03 11:17:06 发布

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

如何将列表转换为字典。我有一个数据以单行的形式存储在DB(sqllite)中,其格式类似于Python和字典,键:值对。数据如下。 "CashVal":"10000.00", "UID":"user01@test.net", "UPWD":"user01#password", "MaxSlots":"7", "MaxSlotsToFill":"5", "MinDollar":"1000"

如果我打印结果集,这就是我得到的

(u'"CashVal":"10000.00", "UID":"user01@test.net", "UPWD":"user01#password", "MaxSlots":"7", "MaxSlotsToFill":"5", "MinDollar":"1000"',)

当我查询它时,返回的结果是一个“列表”-如何将该列表转换为字典?我试过用从钥匙听写()

如何将列表/结果集转换为键/值对字典。你知道吗

EDIT (adding code sample and output)

sql_stmt = "select value from configs where key = 'base_configs'"
rows = execute_sql_return_results(sql_stmt)
print (rows)
print (rows[0])
print (rows[0][0])
s_dict={str(rows[0][0])}
print (s_dict)
print (s_dict["UID"])

exit()

[(u'“CashVal”:10000.00,“UID”:user01@test.net“,”UPWD“:”user01#password“,”MaxSlots“:7,”MaxSlotsToFill“:5,”MinDollar“:1000”,)]

(u'“CashVal”:10000.00,“UID”:user01@test.net“,”UPWD“:”user01#password“,”MaxSlots“:7,”MaxSlotsToFill“:5,”MinDollar“:1000”,)

“CashVal”:10000.00,“UID”:user01@test.net“,”UPWD“:”user01#password“,”MaxSlots“:7,“MaxSlotsToFill”:5,“MinDollar”:1000

设置(['“CashVal”:10000.00,“UID”:user01@test.net“,”UPWD“:”user01#password“,”MaxSlots“:7,“MaxSlotsToFill”:5,“MinDollar”:1000'])

回溯(最近一次呼叫): 文件“gp\ U模型_交易员.py,第283行 打印(s_dict[“UID”]) TypeError:“set”对象没有属性“getitem


Tags: test列表uidnet字典passworddictrows
1条回答
网友
1楼 · 发布于 2024-10-03 11:17:06

如注释中所述,您需要获取字符串并在其周围环绕{},以便它现在看起来像字典的Json表示形式。现在可以使用json.loads将它从Json字符串转换回字典:

import json

s = u'"CashVal":"10000.00", "UID":"user01@test.net", "UPWD":"user01#password", "MaxSlots":"7", "MaxSlotsToFill":"5", "MinDollar":"1000"'
d = json.loads('{' + s + '}')

看起来您正在运行python2。您将得到一个字典,它的键和值是unicode字符串。如果希望这些是str类型,可以使用字典理解转换键和值:

d = {str(k): str(v) for k, v in d.items()}

相关问题 更多 >