SQLite和tkintetable

问题描述 投票:0回答:1

我试图使用tkintertable可视化SQLite查询,但我不确定如何正确格式化我的结果。

当我运行此查询时

c.execute("SELECT type, effort FROM efforts WHERE datum =?", (time.strftime("%d:%m:%Y").replace(":", "."),))

我得到一个输出

[('type1', effort1), ('type2', effort2)]

另一方面,tkintertable需要输入

{0: {'type': type1, 'effort': effort1}, 1: {'type': type2, 'effort': effort2}}

有没有办法以这种方式格式化查询输出?

python sqlite tkinter
1个回答
0
投票

正如@stovfl所提到的,你无法明确地改变告诉cursor对象如何格式化其查询输出。之后,您将光标返回的查询输出转换为所需的表单。

如上所述,您的输出如下:[('type1', 'effort1'), ('type2', 'effort2')]。要将其转换为字典:

output = cursor.fetchall() #output from query
output_dict = {}
for index in range(len(output)): #use an index to create new dictionary elements
    data = output[index] #use that index to find the next piece of data to insert into output dictionary
    output_dict[index] = {'type':  data[0], 'effort': data[1]} #create new dictionary element, using 
    #the index as the key and setup a nested dictionary as the value associated with the key

输出:

0 {'type': 'type1', 'effort': 'effort1'}
1 {'type': 'type2', 'effort': 'effort2'}
© www.soinside.com 2019 - 2024. All rights reserved.