I’m working with TMDB API and i want to get the specific video from a dictionary of videos that is the main trailer of a movie.
movie_video_request = requests.get("https://api.themoviedb.org/3/movie/" + str(movie_id) + "/videos?api_key=" + TMDB_API_KEY)
movie_video_results = movie_video_request.json()
movie_videos = movie_video_results['results']
newDict = dict()
for key,value in movie_videos.items():
if key == 'name' and value == 'Official Trailer':
newDict[key] = value
return render(request, 'Movie Details.html', {'newDict ':newDict })
My API response
"results": [
{
"iso_639_1": "en",
"iso_3166_1": "US",
"name": "Walking Corpses Clip",
"key": "GGe_h2MWMrs",
"site": "YouTube",
"size": 1080,
"type": "Clip",
"official": true,
"published_at": "2022-01-29T17:00:39.000Z",
"id": "61f77629bb105700a0b16a3f"
},
{
"iso_639_1": "en",
"iso_3166_1": "US",
"name": "Official Trailer",
"key": "JfVOs4VSpmA",
"site": "YouTube",
"size": 1080,
"type": "Trailer",
"official": true,
"published_at": "2021-11-17T01:30:05.000Z",
"id": "61945b8a4da3d4002992d5a6"
},
{
"iso_639_1": "en",
"iso_3166_1": "US",
"name": "The New Spider-Man Title is…",
"key": "iqyPvdsOWKk",
"site": "YouTube",
"size": 1080,
"type": "Teaser",
"official": true,
"published_at": "2021-02-24T17:44:20.000Z",
"id": "60378fdcd132d60040a45d96"
}
]
I want my result to be that of the Official Trailer
{key": "JfVOs4VSpmA"}
so that I can place it in an <a href> tag
<a href="https://www.youtube.com/watch?v={{ newDict.value }}">
<p> Watch Trailer </p>
</a>
I’m getting an error
Exception Value: 'list' object has no attribute 'items'
>Solution :
If you look closer, you will see that movie_videos is a list. If you want to iterate over it, just drop the .items().
Later you have to change the loop a bit, because we are going through a list of dictionaries, not a dictionary of dictionaries.
It might look something like this:
newDict = dict()
for movie in movie_videos:
if movie['name'] == 'Official Trailer':
newDict['key'] = movie['key']