python中数据文件值为元组列表的嵌套字典

python中数据文件值为元组列表的嵌套字典,python,Python,请帮忙。我有一个包含4列(userid、movieid、score、timestamp)的数据文件,如下所示: 196 242 3 881250949 186 302 3 891717742 22 377 1 878887116 196 51 2 880606923 62 257 2 879372434 我正在尝试创建一个嵌套字典,该字典应如下所示: 196 242 3 881250949 186 302 3 891717742 22 377 1 878

请帮忙。我有一个包含4列(userid、movieid、score、timestamp)的数据文件,如下所示:

196 242 3   881250949
186 302 3   891717742
22  377 1   878887116
196 51  2   880606923
62  257 2   879372434
我正在尝试创建一个嵌套字典,该字典应如下所示:

196 242 3   881250949
186 302 3   891717742
22  377 1   878887116
196 51  2   880606923
62  257 2   879372434
用户={'196':[('242','3'),('51','2')],'186':['302','3']…}

我的代码只为每个用户标识提取一个元组(movieid,score):

def create_users_dict():
    try:
        users = {}
        for line in open('u.data'):
            (id, movieid, rating, timestamp) = line.split('\t')[0:4]
            users[id] = (movieid, rating)
    except IOError as ioerr:
        print('There is an error with the file:' + str(ioerr))
    return users
users = create_users_dict()
用户={'196':('51','2'),'186':('302','3')…}

使用:

输出

{'196': [('242', '3'), ('51', '2')], '62': [('257', '2')], '186': [('302', '3')], '22': [('377', '1')]}
一种可能的替代方法是检查键(
uid
)是否在字典中,以防丢失,使用空列表初始化值,然后简单地追加

def create_users_dict():
    try:
        users = {}
        for line in open('u.dat'):
            uid, movie_id, rating, timestamp = line.split()
            if uid not in users:
                users[uid] = []
            users[uid].append((movie_id, rating))
        return users
    except IOError as ioerr:
        print('There is an error with the file:' + str(ioerr))
作为旁注,您不应该使用
id
作为名称,因为它会隐藏内置函数