简体   繁体   中英

Storing dictionary data using Python3 and SQLlite

Here is my code:

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  

Here is my data:

[{1, 'lll', ‘lll', 'lll', '', ‘1’,  'lobio', 'c:/'},
{2, 'test', ‘test3', 'blob', 'blah', ‘1’,  'lio', 'c:/'},
{3, 'ledere', ‘copsssss', 'reds', 'server', ‘0’,  'lobio', 'c:/'}]

Here is what I want in a dictionary

{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:/'}}

You have two nested for loops, for all row indexes, and for all rows, so the innermost line sees all combinations of i and row (3×3), even those where these two do not match.

You have to use a single loop:

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

And a dictionary with consecutive numbers as keys is pointless; it would be simpler to use an array as return value:

cursor.execute("...")
column_names = [s[0] for s in cursor.description]
downloader = [dict(zip(column_names, row)) for row in cursor]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM