Python 如何从函数中的函数中提取键值?
我有字典格式的电影数据,如下例所示:Python 如何从函数中的函数中提取键值?,python,python-3.x,Python,Python 3.x,我有字典格式的电影数据,如下例所示: {'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
{'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\u from_tastedive(movies),以获取来自tastedive的电影数据(第1部分),然后定义了第二个函数(第2部分)extract_movie\u title以获取电影标题
获取KeyError:KeyError:第23行类似
-我正在runestone学习环境中运行它,它还显示:{'error':'响应不能解释为json。请尝试打印.text属性'}。
-如果我尝试打印.text,它会说AttributeError:“dict”对象在第21行没有属性“text”
第一部分
第二部分
预期的结果应该是:['Startup Kids'、'Charlie Chaplin']、'Venus In Fur'、'Loving'、'African Queen']但是得到一个关键错误:在第23行类似您要查找的信息在t['Simular'['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))
输出:
您要查找的信息位于t['Simular']['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))
输出:
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))