基于JSON电影数据生成影片名-演员数字典的Python实现求助
问题:修正Python代码实现单部电影演员数量统计
需求说明
我有一个存储电影数据的JSON文件,希望生成一个以电影标题为键、对应影片演员数量为值的字典。以下是JSON文件中的数据示例:
{ "title": "Marie Antoinette", "year": "2006", "genre": "Drama", "summary": "Based on Antonia Fraser's book about the ill-fated Archduchess of Austria and later Queen of France, 'Marie Antoinette' tells the story of the most misunderstood and abused woman in history, from her birth in Imperial Austria to her later life in France.", "country": "USA", "director": { "last_name": "Coppola", "first_name": "Sofia", "birth_date": "1971" }, "actors": [ { "first_name": "Kirsten", "last_name": "Dunst", "birth_date": "1982", "role": "Marie Antoinette" }, { "first_name": "Jason", "last_name": "Schwartzman", "birth_date": "1980", "role": "Louis XVI" } ] }
现有问题代码
我编写了一段Python代码,但它错误统计了所有电影的总演员数,而非单部影片的演员数量,作为Python新手寻求代码修正帮助,以下是我的代码:
import json def actor_count(json_data): with open("movies_db.json", 'r') as file: data = json.load(file) for t in data: title = [t['title'] for t in data] for element in data: for actor in element['actors']: rolee = [actor['role'] for movie in data for actor in movie['actors']] len_role = [len(role)] newD = dict(zip(title, len_role)) print(newD) json_data = open('movies_db.json') actor_count(json_data)
代码修正方案
原代码的核心问题是嵌套逻辑混乱,多次全局遍历电影数据,导致统计的是所有电影的演员总数,而非单部电影的演员数。同时存在参数冗余、变量定义错误等问题,以下是修正后的代码:
针对多电影列表的JSON文件(顶层是数组)
import json def actor_count(): with open("movies_db.json", 'r') as file: movies_data = json.load(file) actor_count_dict = {} # 遍历每一部电影,单独统计演员数量 for movie in movies_data: actor_count_dict[movie['title']] = len(movie['actors']) print(actor_count_dict) actor_count()
针对单电影对象的JSON文件(顶层是单个对象)
如果你的JSON文件只存了一部电影数据,可使用以下代码:
import json def actor_count(): with open("movies_db.json", 'r') as file: movie_data = json.load(file) actor_count_dict = {movie_data['title']: len(movie_data['actors'])} print(actor_count_dict) actor_count()
修正说明
- 移除了无用的
json_data参数,直接在函数内完成文件读取(若需要灵活指定文件路径,可将路径设为函数参数) - 遍历逻辑简化为逐个处理单部电影,直接取当前电影的
actors列表长度,确保统计的是单部影片的演员数 - 字典构建逻辑清晰,每处理一部电影就将标题和对应演员数存入字典
内容的提问来源于stack exchange,提问作者P0ffee
相关产品推荐
相关产品推荐

