about python, I can't understand the example provided in a book
Question: I'm a new learner about python and there are some problems when I try to
repeat the example provided in a guide book. This example is about
recommendation algorithm. This example is trying to implement an item list
which stores the users having rated the particular item. this is the
codes(python 2.7)

    
    
    def UserSimilarity(train):
        #build inverse table for item_users
        item_users=dict()
        for u,items in train.items():
            for i in items.keys():
                if i not in item_users:
                    item_users[i]=set()              
                item_users[i].add(u)
    
    
        #calculate co-rated items between users
        C=dict()
        N=dict()
        for i, users in item_users.items():
            print i,users
            #print N[u]
            for u in users:
                N[u]=N[u]+1
                print N[u]
                for v in users:
                    print C[u][v]
                    if u==v:
                        continue
                    C[u][v]=C[u][v]+1
    
        #calculate finial similarity matrix W
        W=dict()
        for u, related_users in C.items():
            for v, cuv in related_users.items():
                W[u][v]=cuv/math.sqrt(N[u]*N[v])
        return W
    

ps: the data format of 'train' is a dictionary and like
`{UserId1:{ItemId1:Ratings1,ItemId2,Rating2,...},...}`

The problem I met is that

    
    
    Traceback (most recent call last):
      File "D:\Users\Administrator\workspace\GroupLens\src\test3.py", line 82, in <module>
        UserSimilarity(train_dic)
      File "D:\Users\Administrator\workspace\GroupLens\src\test3.py", line 66, in UserSimilarity
        N[u]=N[u]+1
    KeyError: '3'
    

I don't know how to improve it and hope someone would help me! Thanks a lot!!


Answer: The main issue is that you are defining a new dictionary (`N = dict()`), and
then iterating through your `users`, trying to create a dictionary key based
on a given user. That part is fine, but the issue arises when you do this:

    
    
    N[u]=N[u]+1
    

Assigning a value to the dictionary is fine, but look at the right side - you
are trying to assign to `N[u]` the value of `N[u] + 1`, when `N[u]` doesn't
exist yet (hence the error). I'm not 100% sure what the overall goal is (so
this may be misguided), but if your aim is to increment a number based on how
many times a user occurs, you could use a `defaultdict`, which is created with
a type as an argument (here an `int`). This means that if the key is not found
(as in your error above), the default value is based on the type you declared
(here `0`):

    
    
    In [1]: from collections import defaultdict
    
    In [2]: N = defaultdict(int)
    
    In [3]: users = [1, 2, 3, 2, 1, 2]
    
    In [4]: for u in users:
       ...:     N[u] += 1
       ...:     
       ...:     
    
    In [5]: N
    Out[5]: defaultdict(<type 'int'>, {1: 2, 2: 3, 3: 1})
    

Alternatively, you could use a normal dictionary but with the `get` method,
which returns a value if it is found but returns a default if not (a default
that you can specify yourself):

    
    
    In [1]: N = dict()
    
    In [2]: users = [1, 2, 3, 2, 1, 2]
    
    In [3]: for u in users:
       ...:     N[u] = N.get(u, 0) + 1
       ...:     
       ...:     
    
    In [4]: N
    Out[4]: {1: 2, 2: 3, 3: 1}
    

