有人能帮我从字典中创建字典吗
我已经建立了一个对IMDB的API调用(使用imdbpy),这样我就可以检索电影信息字典——包括电影中主要演员的名字。此API调用工作正常
但是,当我尝试从第一个字典中创建第二个字典,如{'actor_name': ['film names,....']}
时,我得到的结果是,每个电影都有自己的嵌套元组,我想要的是电影的简单列表作为键的值
下面是我根据API制作的第一本电影和演员词典的示例:
# Dictionary structure is:
# Key = Name of Film,
# Value = imdb id of film, year of issue of film, main actor name, genre of film
films = {'The Matrix': ['0133093', 1999, ['Keanu Reeves'], ['Action', 'Sci-Fi']], 'Little Buddha': ['0107426', 1993, ['Keanu Reeves'], ['Drama']], 'The First Wives Club': ['0116313', 1996, ['Goldie Hawn'], ['Comedy']], 'Replicas': ['4154916', 2018, ['Keanu Reeves'], ['Drama', 'Sci-Fi', 'Thriller']], 'Siberia': ['6494418', 2018, ['Keanu Reeves'], ['Crime', 'Romance', 'Thriller']], 'Death Becomes Her': ['0104070', 1992, ['Meryl Streep'], ['Comedy', 'Fantasy', 'Horror']], 'Godzilla vs. Kong': ['5034838', 2021, ['Alexander Skarsgård'], ['Action', 'Sci-Fi', 'Thriller']], 'The Da Vinci Code': ['0382625', 2006, ['Tom Hanks'], ['Mystery', 'Thriller']], 'Overboard': ['0093693', 1987, ['Goldie Hawn'], ['Comedy', 'Romance']], 'The Big Blue': ['0095250', 1988, ['Rosanna Arquette'], ['Adventure', 'Drama', 'Sport']]}
这是我用来制作第二个动作名称字典的代码,作为键,电影名称作为值:
cast_names = {}
for k, v in films.items():
film = k
for i in v[2]:
key = i
if key in cast_names:
cast_names[key] = (cast_names[key], k)
else:
cast_names[key] = k
print(cast_names)
当我试图用以下代码建立一个{'actor_name':['film names'…]}字典时,我得到了如下结果:
cast_names = {'Keanu Reeves': ((('The Matrix', 'Little Buddha'), 'Replicas'), 'Siberia'), 'Goldie Hawn': ('The First Wives Club', 'Overboard'), 'Meryl Streep': 'Death Becomes Her', 'Alexander Skarsgård': 'Godzilla vs. Kong', 'Tom Hanks': 'The Da Vinci Code', 'Rosanna Arquette': 'The Big Blue'}
看起来每部电影都是嵌套的元组。我想要的是:
{'Keanu Reeves': ['The Matrix', 'Little Buddha', 'Replicas', 'Siberia'], 'Goldie Hawn':[.........] etc
有什么建议吗
谢谢
只需使用
[]
和.append()
创建一个列表输出:
相关问题 更多 >
编程相关推荐