0

Using Python, I've had success with selecting and updating values by row using mysql.connector with variables in my queries and defining variables (strings and integers) from query results.

I'd like to select all values from two columns in a SQL table and pass them to a dictionary, with one column holding the keys and the other column holding the values paired by table row.

I attempted this. It failed:

cursor.execute('SELECT id, name FROM colors')
for (id, name) in cursor:
   test001 = dict([id, name]) 
bblohowiak
  • 103
  • 4

2 Answers2

0

You need to initialize an empty dict then add an entry to it for each row in your result set.

cursor.execute('SELECT id, name FROM colors')
test001 = {}
for (id, name) in cursor:
   test001[id] = name
Alan Hoover
  • 1,430
  • 2
  • 9
  • 13
0

Assuming, that the fetched rows go to a list of tuples, you can just build a dictionary from it in Python 3, like:

selection = []
exec = cursor.execute('SELECT id, name FROM colors')
selection.extend(exec.fetchall())
d_selection = dict(selection)
JeyJey
  • 41
  • 4