在for循环中添加了额外的字典键

2024-10-05 15:28:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个python函数,它以电影标题作为键,以电影中的表演者列表作为值,然后返回一个新的dict,以表演者作为键,以电影中的表演者作为值。这段代码很接近,但每次运行都返回不同的结果

以下是原始函数调用:

    movies = {"How to Be Single": ["Alison Brie", "Dakota Johnson",
                               "Rebel Wilson"],
              "The Lego Movie": ["Will Arnett", "Elizabeth Banks",
                             "Alison Brie", "Will Ferrell"]}
    print(stars,movies)

代码如下:

def stars(movies):
# create a new dictionary
films_dict= {}
performances_films = []

# for each movie actor, add as key to new_dict
for movie, actors in movies.items():
    for actor in actors:
        if not actor in films_dict.keys():
            #print(actor)
            performances_films = []
            performances_films.append(movie)
            films_dict[actor] = performances_films
        else:
            performances_films.append(movie)
            films_dict[actor] = performances_films

return(films_dict)

以下是输出:

RUN 1
    {'Rebel Wilson': ['How to Be Single'], 'Will Ferrell': ['The Lego 
    Movie'], 
    'Will Arnett': ['The Lego Movie'], 'Elizabeth Banks': ['The Lego Movie', 
    'The Lego Movie'], 'Alison Brie': ['The Lego Movie', 'The Lego Movie'], 
    'Dakota Johnson': ['How to Be Single']}

RUN 2
{'Will Arnett': ['The Lego Movie'], 'Dakota Johnson': ['How to Be Single'], 'Elizabeth Banks': ['The Lego Movie', 'The Lego Movie'], 'Rebel Wilson': ['How to Be Single'], 'Will Ferrell': ['The Lego Movie'], 'Alison Brie': ['The Lego Movie', 'The Lego Movie']}

我认为它要么在每次运行时以不同的顺序遍历dict项,要么从一次运行到下一次运行保存数据。不管怎样,我似乎都解决不了


Tags: thetobemoviesmoviewilldicthow
3条回答

我真的不明白你为什么要留着一张performances_films清单。您可以只使用前面在dict本身中创建的那些

以下是我认为可行的方法:

def stars(movies):
    # create a new dictionary
    films_dict= {}

    # for each movie actor, add as key to new_dict
    for movie, actors in movies.items():
        for actor in actors:
            if not actor in films_dict.keys():
                performances_films = []
                performances_films.append(movie)
                films_dict[actor] = performances_films
            else:
                films_dict[actor].append(movie)

    return(films_dict)

代码中的错误是list实例performances_films从一个循环迭代持续到下一个循环迭代。这就是为什么(比如)Alison Brie把Lego电影列了两次,它本来应该是为另一个演员添加的,但是之前为Alison Brie创建的list实例仍然占据了名称槽performances_films。事实上,看起来多个参与者可能共享同一个list实例

如果在访问字典时使用“default value”概念,可以大大简化代码。这可以通过使用^{}类来完成:

import collections
filmography = collections.defaultdict(list)
for movie, actors in movies.items():
    for actor in actors:
        filmography[actor].append(movie)

或者我更喜欢的方法是香草dict和它的^{}方法:

filmography = {}                     
for movie, actors in movies.items():
    for actor in actors:
        filmography.setdefault(actor, []).append(movie)

无论哪种方式,您都可以统一地对待每部新电影,而不必显式地测试演员先前的filmography成员资格

movies = {"How to Be Single": ["Alison Brie", "Dakota Johnson",
                               "Rebel Wilson"],
              "The Lego Movie": ["Will Arnett", "Elizabeth Banks",
                             "Alison Brie", "Will Ferrell"]}
stars = {}
for movie, v in movies.items():
    for star in v:
        if star in stars:
            stars[star].append(movie)
        else:
            stars[star] = [movie]

print(stars)

印刷品:

{'Alison Brie': ['How to Be Single', 'The Lego Movie'], 'Dakota Johnson': ['How to Be Single'], 'Rebel Wilson': ['How to Be Single'], 'Will Arnett': ['The Lego Movie'], 'Elizabeth Banks': ['The Lego Movie'], 'Will Ferrell': ['The Lego Movie']}

相关问题 更多 >