I have created a database table called fruits with 3 columns, id(int primary key), fruits(text) and weight(float).
id | fruit | weight |
---|---|---|
1 | Apple | 80.5 |
2 | Pear | 150.8 |
3 | Kiwi | 69 |
How do I create a dictionary and add all the fruits and weight as key-value pairs to the dictionary?
import sqlite3
conn = sqlite3.connect("database.db")
sql = """SELECT fruit,weight FROM fruits"""
cursor = conn.execute(sql)
data = cursor.fetchall()
fruitweight= {}
i = 0
while(i < len(data)):
fruitweight['<fruitname>'] = <fruitweight>
i = i 1
CodePudding user response:
Something like this:
for row in data:
name, weight = row
fruitweight[name] = weight
fetchall()
returns a list of tuples of values from the database according to your query. The above unpacks the tuples into two variables.
If you want to get fancy, you can use a dictionary comprehension with tuple unpacking:
fruitweight = {name: weight for name, weight in data}
And finally, execute()
actually returns a cursor that you can iterate over, so I think your code can be reduced to the following:
import sqlite3
conn = sqlite3.connect("database.db")
sql = """SELECT fruit,weight FROM fruits"""
fruitweight = {name: weight for name, weight in conn.execute(sql)}
CodePudding user response:
I don't think that the cursor is correct but you should use for loop instead:
import sqlite3
conn = sqlite3.connect("database.db")
cur = conn.cursor()
sql = """SELECT fruit,weight FROM fruits"""
cur.execute(sql)
data = cur.fetchall()
fruitweight= {}
for i in data:
fruitweight[i[0]] = i[1]
conn.close()
print(fruitweight)
CodePudding user response:
You could do it like this:
import sqlite3
with sqlite3.connect('/Users/andy/andy') as conn:
cursor = conn.execute('select fruit, weight from fruits')
D = dict()
for row in cursor.fetchall():
D[row[0]] = row[1]
print(D)