-1

I want to calculate similarity between users, but cannot add the value to empty dictionary.

Here is my code:

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
Foon
  • 5,830
  • 11
  • 38
  • 41
amy
  • 1
  • 1

1 Answers1

1

Are you trying to do this?

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

When you do w[u][v] the [v] is accessing something that does not exist. You must create [u] first.

Zach Kramer
  • 193
  • 1
  • 1
  • 7
  • Yes, thank u! I'm really a newbie to python. – amy Dec 18 '17 at 17:22
  • 1
    you might want to look at doing from collections import defaultdict and setting w to be defaultdict(dict) (or if you want to go crazy, see https://stackoverflow.com/questions/5029934/python-defaultdict-of-defaultdict ... but that's getting a bit a far from python newbie) ... defaultdict will detect if you try to access a key you haven't defined yet and make it an object of whatever type you pass in (in your case dict) ... this would allwo you to skip the if u not in w.keys() step) – Foon Dec 18 '17 at 19:57