0

I have data about the movies in the format of the dictionary, like the example below:

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

I need to extract movie names from that, but I am getting different errors on the go. Have been trying many things, but haven't found a solution.

I created the function get_movies_from_tastedive(movies), to have my data on movies from TasteDive (Part 1) and then I defined a second function, (Part 2) extract_movie_titles for getting the movie titles.

Getting a KeyError: KeyError: Similar on line 23 - I am running it in runestone learning environment and it also shows: {'error': 'Response not interpretable as json. Try printing the .text attribute'}. - If I try to print .text it says that AttributeError: 'dict' object has no attribute 'text' on line 21

Part 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()

Part 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 expected result should be: ['The Startup Kids', 'Charlie Chaplin’], ‘Venus In Fur’, ‘Loving’, ‘The African Queen’] but getting a KeyError: Similar on line 23

1 Answer 1

2

The info you are looking for is in t['Similar']['Results']

Following code worked for me :

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))

Output: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.