Я хочу присвоить переменные первым трем заголовкам, возвращенным в моем ответе - PullRequest
0 голосов
/ 13 июля 2020

Но в некоторых случаях «результаты» меньше 3, и я получаю ошибку «вне допустимого диапазона». Итак, как мне назначить столько переменных, сколько есть результатов ('total_results') в моем ответе? Это мой первый вопрос, извините, если он сформулирован неправильно.

import requests, json

response  = requests.get('https://api.themoviedb.org/3/search/movie?api_key=xxxxxxxxxxxxx&language=en-US&query=Batman%20Begins&page=1&include_adult=false')

result_dict = response.json()


#copy-pasting what fetched response looks like

result_dict = {'page': 1, 'total_results': 2, 'total_pages': 1, 'results': [{'popularity': 34.077, 'vote_count': 14576, 'video': False, 'poster_path': '/8RW2runSEc34IwKN2D1aPcJd2UL.jpg', 'id': 272, 'adult': False, 'backdrop_path': '/lh5lbisD4oDbEKgUxoRaZU8HVrk.jpg', 'original_language': 'en', 'original_title': 'Batman Begins', 'genre_ids': [28, 80, 18], 'title': 'Batman Begins', 'vote_average': 7.7, 'overview': 'Driven by tragedy, billionaire Bruce Wayne dedicates his life to uncovering and defeating the corruption that plagues his home, Gotham City.  Unable to work within the system, he instead creates a new identity, a symbol of fear for the criminal underworld - The Batman.', 'release_date': '2005-06-10'}, {'popularity': 2.786, 'id': 498471, 'video': True, 'vote_count': 3, 'vote_average': 8.7, 'title': 'Batman: The Animated Series - The Legend Begins', 'release_date': '1992-04-23', 'original_language': 'en', 'original_title': 'Batman: The Animated Series - The Legend Begins', 'genre_ids': [16, 28], 'backdrop_path': None, 'adult': False, 'overview': 'Taking a cue from the caped crusader\'s comic book rebirth in Frank Miller\'s The Dark Knight Returns and Batman: Year One, this 1992 animated series saved the TV Batman from a fate worse than camp and drew an unexpected audience for an afternoon cartoon: adults. The initial five episodes gathered here feature such supervillains as Man-bat, the Scarecrow, and Poison Ivy, but the deliciously demented Joker (voiced by Mark Hamill) steals the show in his two appearances, especially in the twisted "Christmas with the Joke." Escaping Arkham Asylum in a rocket-powered Christmas tree, the clown prince of crime preempts a TV showing of It\'s a Wonderful Life with his own homicidal holiday treat. It\'s a solid start to a sleek, stylized, smartly written series that only improved with time. Ages 7 and up.', 'poster_path': '/A3VfRAu8UqN13Jdr8JYh3Kb48DY.jpg'}]}


title1 = ((result_dict.get('results')[0])['title'])
title2 = ((result_dict.get('results')[1])['title'])
title3 = ((result_dict.get('results')[2])['title'])

Ответы [ 2 ]

0 голосов
/ 13 июля 2020

Вы можете попробовать:

result_dict = {'page': 1, 'total_results': 2, 'total_pages': 1, 'results': [{'popularity': 34.077, 'vote_count': 14576, 'video': False, 'poster_path': '/8RW2runSEc34IwKN2D1aPcJd2UL.jpg', 'id': 272, 'adult': False, 'backdrop_path': '/lh5lbisD4oDbEKgUxoRaZU8HVrk.jpg', 'original_language': 'en', 'original_title': 'Batman Begins', 'genre_ids': [28, 80, 18], 'title': 'Batman Begins', 'vote_average': 7.7, 'overview': 'Driven by tragedy, billionaire Bruce Wayne dedicates his life to uncovering and defeating the corruption that plagues his home, Gotham City.  Unable to work within the system, he instead creates a new identity, a symbol of fear for the criminal underworld - The Batman.', 'release_date': '2005-06-10'}, {'popularity': 2.786, 'id': 498471, 'video': True, 'vote_count': 3, 'vote_average': 8.7, 'title': 'Batman: The Animated Series - The Legend Begins', 'release_date': '1992-04-23', 'original_language': 'en', 'original_title': 'Batman: The Animated Series - The Legend Begins', 'genre_ids': [16, 28], 'backdrop_path': None, 'adult': False, 'overview': 'Taking a cue from the caped crusader\'s comic book rebirth in Frank Miller\'s The Dark Knight Returns and Batman: Year One, this 1992 animated series saved the TV Batman from a fate worse than camp and drew an unexpected audience for an afternoon cartoon: adults. The initial five episodes gathered here feature such supervillains as Man-bat, the Scarecrow, and Poison Ivy, but the deliciously demented Joker (voiced by Mark Hamill) steals the show in his two appearances, especially in the twisted "Christmas with the Joke." Escaping Arkham Asylum in a rocket-powered Christmas tree, the clown prince of crime preempts a TV showing of It\'s a Wonderful Life with his own homicidal holiday treat. It\'s a solid start to a sleek, stylized, smartly written series that only improved with time. Ages 7 and up.', 'poster_path': '/A3VfRAu8UqN13Jdr8JYh3Kb48DY.jpg'}]}
titles = []

for result_id in range(result_dict["total_results"]):
    titles.append(result_dict["results"][result_id]["title"])
print(titles)

Вывод:

['Batman Begins', 'Batman: The Animated Series - The Legend Begins']
0 голосов
/ 13 июля 2020
titles = list()
for idx in range(result_dict['total_results']):
    titles.append(result_dict['results'][idx])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...