Skip to content
Advertisement

Python add items into dictionary from database table (sqlite3)

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?

Advertisement

Answer

Something like this:

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:

And finally, execute() actually returns a cursor that you can iterate over, so I think your code can be reduced to the following:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement