首页 > 解决方案 > 如何从函数内的函数中提取键值?

问题描述

我有字典格式的电影数据,如下例所示:

 {'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

标签: pythonpython-3.x

解决方案


您正在寻找的信息在 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))

输出: 在此处输入图像描述


推荐阅读