如何在python迭代中向空嵌套字典添加值
我想计算用户之间的相似性,但无法将值添加到空字典中 这是我的密码:如何在python迭代中向空嵌套字典添加值,python,dictionary,Python,Dictionary,我想计算用户之间的相似性,但无法将值添加到空字典中 这是我的密码: data={'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}, 'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.
data={'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},
'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5,
'Just My Luck': 1.5, 'The Night Listener': 3.0},
'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, 'You, Me and Dupree': 2.5},
'Mick LaSalle': {'Just My Luck': 2.0, 'Lady in the Water': 3.0,'Superman
Returns': 3.0, 'The Night Listener': 3.0, 'You, Me and Dupree': 2.0},
'Jack Matthews': {'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}}
df = pd.DataFrame(data)`
def usersimilarity(df):
w = dict()
for u in df.keys():
for v in df.keys():
if u == v:
continue
w[u][v] =
len(set(df[u])&set(df[v]))/math.sqrt(len(df[u])*len(df[v])*1.0)
return w
你想这么做吗
def usersimilarity(df):
w = dict()
for u in df.keys():
for v in df.keys():
if u == v:
continue
if u not in w.keys():
w[u] = dict()
w[u][v] = len(set(train[u])&set(train[v]))/math.sqrt(len(train[u])*len(train[v])*1.0)
return w
当您执行
w[u][v]
操作时,[v]
正在访问不存在的内容。您必须首先创建[u]
。代码的结果是什么?您希望得到什么?顺便说一句,您粘贴的代码中有一些错误。什么是火车?我的错,已经编辑好了。是的,谢谢!我真的是一个python新手。你可能想看看如何从集合导入defaultdict并将w设置为defaultdict(dict)(或者如果你想发疯,请看……但这离python新手有点远了)。。。defaultdict将检测您是否尝试访问尚未定义的密钥,并使其成为您传入的任何类型的对象(在您的情况下为dict)。。。如果您不在w.keys()步骤中,则可以跳过此步骤)