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?
x
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
Advertisement
Answer
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)}