当我从电影数据字典制作字典时,如何停止生成嵌套元组?

How do I stop generating nested tuples when I make a dictionary from a dictionary of film data?

谁能帮忙从字典创建字典?

我已经构建了一个 API 调用 IMDB(使用 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()


for k, v in films.items():
    film = k
    for i in v[2]:
        key = i
        if key in cast_names:
            cast_names[key].append(k)
        else:
            cast_names[key] = [k]
print(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']}