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

时间:2019-01-29 18:36:05

标签: python dictionary for-loop

我试图编写一个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项目,要么将数据从一次运行保存到下一次。无论哪种方式,我似乎都无法解决。

3 个答案:

答案 0 :(得分:1)

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']}

答案 1 :(得分:0)

我真的不明白为什么要保留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)

答案 2 :(得分:0)

您的代码中的错误是list实例performances_films从一个循环迭代到下一个循环一直存在。这就是为什么(说)艾莉森·布里(Alison Brie)两次将《乐高大电影》(Lego Movie)列出来的原因-确实应该为另一个演员添加它,但是先前为艾莉森·布里(Alison Brie)创建的list实例仍使用该名称插槽performances_films。实际上,似乎多个参与者可能正在共享同一个list实例。

如果在访问字典时使用“默认值”概念,则可以大大简化代码。这可以通过使用collections.defaultdict类来完成:

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

或者我更喜欢的方式是使用香草dict及其setdefault()方法:

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

无论哪种方式,您都可以统一对待每部新电影,而不必明确测试演员的filmography先前成员身份。