Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python数据库中的嵌套字典_Python_Dictionary - Fatal编程技术网

python数据库中的嵌套字典

python数据库中的嵌套字典,python,dictionary,Python,Dictionary,python中的以下代码从数据表中提取所有行: 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

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

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}}

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

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