-1
users = {'196': ('110', '1'), '186': ('269', '1'), '22': ('68', '4'), '196': ('650', '3')}
movies = {'110': 'Operation Dumbo Drop (1995)', '186': 'Blues Brothers, The (1980)',  '269': 'Full Monty, The (1997)', '68': 'Crow, The (1994)', '650': 'Seventh Seal, The (Sjunde inseglet, Det) (1957)'}

My code to create a nested dictionary with keys a unique list of users (keys from users) but using keys from movies to replace values of movies IDs (first item of value list from users) and keeping scores (second item of value list from users) is:

users_preference = {k: list(set().union((*map(lambda x: [x for x in movies.values()], v[0])) )) for k, v in users.items() }

But this returns all movies for each user, and I don't know how to add scores to this. Could you please help? Thank you.

The expected output is similar to:

users_preference = {'196': {'Operation Dumbo Drop (1995)': '1', 'Seventh Seal, The (Sjunde inseglet, Det) (1957)': '3'}
4

4 回答 4

1

更详细

Dct3 = {}
for k, v in users.items():
  v = list(v)
  v[0] = movies[v[0]]
  Dct3[k] = v

print (Dct3)
#=> {'196': ['Seventh Seal, The (Sjunde inseglet, Det) (1957)', '3'], '186': ['Full Monty, The (1997)', '1'], '22': ['Crow, The (1994)', '4']}
于 2018-11-10T13:24:30.657 回答
1
Dct3 = {k:(movies[v[0]],v[1]) for k, v in users.items()}

保持简单,您可以使用键来访问电影字典中的值。只需将其视为创建一个新元组作为用户中每个键的值。

于 2018-11-10T13:16:02.220 回答
0

你可以发出

{user:(movies[movie_id], score) for user, (movie_id, score) in users.items()}

产生

{'186': ('Full Monty, The (1997)', '1'),
 '196': ('Seventh Seal, The (Sjunde inseglet, Det) (1957)', '3'),
 '22': ('Crow, The (1994)', '4')}

请注意,您的字典中有一个重复键users( '196')。(Daniel Mesejo 在评论中指出。)字典键必须是唯一的,所以users实际上看起来像这样:

>>> users
>>> {'186': ('269', '1'), '196': ('650', '3'), '22': ('68', '4')}

~编辑~

做同样的传统for循环。

result = {}
for user, (movie_id, score) in users.items():
    result[user] = (movies[movie_id], score)
于 2018-11-10T13:25:31.733 回答
0

使用 的格式无法实现预期的输出users,我建议您更改为字典,其中值是元组列表:

users = {'196': [('110', '1'), ('650', '3')], '186': [('269', '1')], '22': [('68', '4')]}
movies = {'110': 'Operation Dumbo Drop (1995)', '186': 'Blues Brothers, The (1980)', '269': 'Full Monty, The (1997)',
          '68': 'Crow, The (1994)', '650': 'Seventh Seal, The (Sjunde inseglet, Det) (1957)'}

user_preference = {user: {movies.get(movie, movie): rank for movie, rank in preferences} for user, preferences in
                   users.items()}

print(user_preference)

输出

{'196': {'Operation Dumbo Drop (1995)': '1', 'Seventh Seal, The (Sjunde inseglet, Det) (1957)': '3'}, '22': {'Crow, The (1994)': '4'}, '186': {'Full Monty, The (1997)': '1'}}
于 2018-11-10T13:34:55.437 回答