下面是我的代码:
def getDownloaders(dbPATH):
with sqlite3.connect(dbPATH) as db:
cursor = db.cursor()
cursor.execute("SELECT * FROM Downloaders")
d = cursor.fetchall()
downloader = {}
column_names = [s[0] for s in cursor.description]
for i in range(len(d)):
for row in d:
downloader[i] = dict(zip(column_names, row))
print(downloader)
return downloader 以下是我的数据:
[{1, 'lll', ‘lll', 'lll', '', ‘1’, 'lobio', 'c:/'},
{2, 'test', ‘test3', 'blob', 'blah', ‘1’, 'lio', 'c:/'},
{3, 'ledere', ‘copsssss', 'reds', 'server', ‘0’, 'lobio', 'c:/'}]这是我想要的字典
{0: {'id': 1, 'Host': 'lll', 'username': 'lll', 'password': 'lll', 'label': 'lll', 'Enabled': 1, 'name': 'lobio', 'file': 'c:/'}, 1: {'id': 2,'Host': 'test', 'username': 'test3', 'password': 'blob', 'label': 'blah', 'Enabled': 1, 'name': 'lio', 'file': 'c:/'}, 2: {'id': 3, 'Host': 'lwderel', 'username': ‘copsssss', 'password': 'reds', 'label': 'server', 'Enabled': 0, 'name': 'lobio', 'file': 'c:/'}}发布于 2018-08-18 18:26:45
您有两个嵌套的for循环,分别用于所有行索引和所有行,因此最内侧的一行可以看到i和row (3×3)的所有组合,即使这两个不匹配的组合也是如此。
您必须使用单个循环:
cursor.execute("...")
column_names = [s[0] for s in cursor.description]
downloader = {}
i = 0
for row in cursor:
downloader[i] = dict(zip(column_names, row))
i += 1使用连续数字作为键的字典是没有意义的;使用数组作为返回值会更简单:
cursor.execute("...")
column_names = [s[0] for s in cursor.description]
downloader = [dict(zip(column_names, row)) for row in cursor]https://stackoverflow.com/questions/51905324
复制相似问题