1

The following code in python extracts all the rows from DATA table:

import MySQLdb

db = MySQLdb.connect("localhost","root","","myDB" )
cursor = db.cursor()
sql = "SELECT user,item,rate FROM data"
cursor.execute(sql)
results = cursor.fetchall()

for row in results:
    name = row[0]
    title = row[1]
    vote = row[2]
    print name,title,vote

db.close()

I want to construct the results according to the following dictionary form. How I can do this?

critics={'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,
'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,
'The Night Listener': 3.0},
'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5,
'Just My Luck': 1.5, 'Superman Returns': 5.0, 'The Night Listener': 3.0,
'You, Me and Dupree': 3.5},
'Michael Phillips': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.0,
'Superman Returns': 3.5, 'The Night Listener': 4.0},
'Claudia Puig': {'Snakes on a Plane': 3.5, 'Just My Luck': 3.0,
'The Night Listener': 4.5, 'Superman Returns': 4.0,
'You, Me and Dupree': 2.5},
'Mick LaSalle': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
'Just My Luck': 2.0, 'Superman Returns': 3.0, 'The Night Listener': 3.0,
'You, Me and Dupree': 2.0},
'Jack Matthews': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
'The Night Listener': 3.0, 'Superman Returns': 5.0, 'You, Me and Dupree': 3.5},
'Toby': {'Snakes on a Plane':4.5,'You, Me and Dupree':1.0,'Superman Returns':4.0}}

2 Answers 2

1
data = {}
for row in results:
   if row[0] not in data:
      data[row[0]] = {}

   data[row[0]][row[1]] = row[2]
Sign up to request clarification or add additional context in comments.

Comments

0

If your rows have same name with different values do this:

res = {}
for row in results:
    name = row[0]
    title = row[1]
    vote = row[2]
    res.get(name, res.update({name: {title: vote}}).update(title: vote})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.