python - 如何从函数内的函数中提取键值?
问题描述
我有字典格式的电影数据,如下例所示:
{'Similar': {'Info': [{'Name': 'Tony Bennett', 'Type': 'music'}], 'Results': [{'Name': 'The Startup Kids', 'Type': 'movie'}, {'Name': 'Charlie Chaplin', 'Type': 'movie'}, {'Name': 'Venus In Fur', 'Type': 'movie'}, {'Name': 'Loving', 'Type': 'movie'}, {'Name': 'The African Queen', 'Type': 'movie'}]}}
我需要从中提取电影名称,但我在旅途中遇到了不同的错误。尝试了很多东西,但没有找到解决方案。
我创建了函数 get_movies_from_tastedive(movies),以获取来自 TasteDive(第 1 部分)的电影数据,然后我定义了第二个函数(第 2 部分)extract_movie_titles 用于获取电影标题。
获取 KeyError:KeyError:第 23 行类似 - 我在 runestone 学习环境中运行它,它还显示:{'error':'Response not interpretable as json. 尝试打印 .text 属性'}。- 如果我尝试打印 .text,它会在第 21 行显示 AttributeError: 'dict' object has no attribute 'text'
第1部分
def get_movies_from_tastedive(movies):
baseurl = "https://tastedive.com/api/similar"
params_diction = {}
params_diction["q"] = movies
params_diction["type"] = "movies"
params_diction["limit"] = 5
movie_resp = requests_with_caching.get(baseurl, params = params_diction)
#print(movie_resp.json())
return movie_resp.json()
第2部分
def extract_movie_titles(movies):
t = get_movies_from_tastedive(movies)
#title = t.text
#print(title)
return [d['Name'] for d in t['Similar']['Info']]
extract_movie_titles(get_movies_from_tastedive("Tony Bennett"))
extract_movie_titles(get_movies_from_tastedive("Bridesmaids"))
预期的结果应该是:['The Startup Kids', 'Charlie Chaplin'], 'Venus In Fur', 'Loving', 'The African Queen'] 但是得到一个 KeyError: Similar on line 23
解决方案
您正在寻找的信息在 t['Similar']['Results']
以下代码对我有用:
d = {'Similar': {'Info': [{'Name': 'Tony Bennett', 'Type': 'music'}], 'Results': [{'Name': 'The Startup Kids', 'Type': 'movie'}, {'Name': 'Charlie Chaplin', 'Type': 'movie'}, {'Name': 'Venus In Fur', 'Type': 'movie'}, {'Name': 'Loving', 'Type': 'movie'}, {'Name': 'The African Queen', 'Type': 'movie'}]}}
def extract_movie_titles(d):
return [m['Name'] for m in d['Similar']['Results']]
print (extract_movie_titles(d))
推荐阅读
- java - Mule Http 连接器提供 BufferInputStream ,它在转换时提供垃圾值
- java - 在 Java 中执行 Linux 命令时,缓冲区读取器添加“[?1034h”作为最后一行
- python - 根据 setup_module 或其他函数的输出动态参数化 pytest 测试函数
- laravel - 检查下一个运行 Laravel 的时间表是什么时候
- sql - SQL Server 选择列中的所有最大和最小数据
- delphi - TDBNavigator 背景透明度颜色错误
- python - 如何使用字典值中的精确字符串创建新列表?
- java - 将响应转换为字符串 JAVA 时出现 500 状态
- c - 如何集成模块?
- java - Jackson - 基于多个属性的自定义 TypeId 解析器