如何反转值为列表的字典?Python电影演员字典转换与查询
问题:反转值为列表的字典并实现演员查电影功能
我需要反转一个值为列表的字典,具体编程任务如下:编写Python程序读取指定文件中的数据,创建以演员/女演员姓名为键、其参演电影列表为值的字典;程序需询问用户输入演员/女演员姓名,并依据字典信息输出该演员参演的所有电影。当前已有一段以电影名为键、参演演员列表为值的代码,现需对其进行修改以满足任务要求。
现有代码
in_file = open("movie and actors.txt", "r") movie_dictionary = {} for line in in_file: movies_and_actors = line.strip().split(', ') movie = movies_and_actors[0] actor = movies_and_actors[1:] movie_dictionary[movie] = actor s = input("Enter an actor/actress name: ") d = [i for i in movie_dictionary if s in movie_dictionary[i]] listToStr = ' and '.join([elem for elem in d]) print("The movies that", s, "starred in are", listToStr) in_file.close()
文件movie and actors.txt内容
La La Land, Ryan Gosling, Emma Stone Blade Runner 2049, Harrison Ford, Ryan Gosling, Ana de Armas Cruella, Emma Stone, Emma Thompson, Joel Fry Iron Man, Robert Downey Jr., Gwyneth Paltrow, Terrence Howard Avatar, Sam Worthington, Zoe Saldana, Sigourney Weaver Star Wars A New Hope, Mark Hamil, Carrie Fisher, Harrison Ford Air Force One, Harrison Ford, Gary Oldman, Glen Close Pretty Woman, Richard Gere, Julia Roberts, Jason Alexander My Best Friend's Wedding, Julia Roberts, dermont Multroney, Cameron Diaz There's Something About Mary, Cameron Diaz, Matt Dillon, Ben Stiller Meet the Parents, Ben Stiller, Robert De Niro, Teri Polo Top Gun Maverick, Tom Cruse, Jennifer Connelly, Miles Teller Black Panther: Wakanda Forever, Letitia Wright, Lupita Nyong'o, Danai Gurira Thor: Love and Thunder, Chris Hemsworth, Natalie Portman, Christian Bale Notting Hill, Hugh Grant, Julia Roberts, Richard McCabe
修改后的代码
# 用with语句自动管理文件,无需手动close with open("movie and actors.txt", "r") as in_file: actor_dict = {} for line in in_file: # 拆分每行数据,去掉首尾空白 parts = line.strip().split(', ') movie_name = parts[0] actors = parts[1:] # 遍历每个演员,构建演员到电影的映射 for actor in actors: # 如果演员不在字典中,初始化空列表 if actor not in actor_dict: actor_dict[actor] = [] # 将当前电影添加到演员的电影列表中 actor_dict[actor].append(movie_name) # 获取用户输入 actor_name = input("请输入演员/女演员姓名:") # 查询并输出结果 if actor_name in actor_dict: movies = actor_dict[actor_name] # 格式化输出电影列表 movie_str = ' 和 '.join(movies) print(f"{actor_name} 参演的电影有:{movie_str}") else: print(f"未找到演员 {actor_name} 的参演记录")
关键修改说明
- 字典反转逻辑:不再以电影为键,而是遍历每个演员,将电影添加到对应演员的列表中,实现从「电影→演员」到「演员→电影」的映射反转
- 文件安全处理:使用
with语句打开文件,程序结束后会自动关闭文件,避免资源泄漏 - 查询逻辑简化:直接通过演员名字作为键从字典中取值,无需遍历整个字典查找,效率更高
- 异常情况处理:增加了演员不存在时的提示,提升用户体验
内容的提问来源于stack exchange,提问作者RykerStrike
相关产品推荐
相关产品推荐

