0

I'll start to say that I am new to Python, so maybe this is a wierd problem,

I got a db with 3 row, I want to loop them in an dictionary, but i only get one row shown on the site, so it's some kind af overwriting every time it loops.

from dbConnect import connect

c, conn = connect()

ranks = c.execute("SELECT * FROM ranks ORDER BY rankid ASC;")

ranks = c.fetchall()

def ranksddl():
   rank_dict = {}

for rank in ranks:
    rank_dict[rank] = rank[2]

return rank_dict
Henrik S
  • 105
  • 1
  • 1
  • 6
  • Related? [DictCursor](http://stackoverflow.com/questions/2180226/python-use-mysqldb-to-import-a-mysql-table-as-a-dictionary). – alecxe Jul 31 '15 at 16:00
  • In your for loop you are assigning the same value -- rank[2] -- to each element in the dictionary (rank_dict). Is that your intention? I think you likely want for rank in ranks: rank_dict[rank] = rank – mba12 Jul 31 '15 at 16:02
  • 1
    you probably want `rank_dict['rank'] = rank` (quotes around the rank inside the square brackets). – hiro protagonist Jul 31 '15 at 20:57

1 Answers1

0

You should have:

ranks = ranks.fetchall()

and not

ranks = c.fetchall()

to get all of the results because the result of the query is stored in the first ranks variable. So if you want to get all the results in one go you should use fetchall() method on that variable and not on the cursor.

doru
  • 9,022
  • 2
  • 33
  • 43