来自数据库python的嵌套字典

时间:2016-01-21 14:38:44

标签: python dictionary

python中的以下代码从DATA表中提取所有行:

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()

我想根据以下字典表单构建结果。 我怎么能这样做?

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 个答案:

答案 0 :(得分:1)

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

   data[row[0]][row[1]] = row[2]

答案 1 :(得分:0)

如果您的行具有相同的名称和不同的值,请执行以下操作:

{{1}}