0

Hi I am trying to make a database using IMDbPY library. But when I try to get name with get('cast'). How can I fix it? Code is below:

from imdb import IMDb
ia = IMDb()
def getmovieID( movie_name ):
    movie = ia.search_movie(movie_name)[0] # a Movie instance.
    get_movie = ia.get_movie(movie.movieID)
    return get_movie

def getcast(movie_name):
    movie = getmovieID(movie_name)
    casts = []
    cast = movie.get('casts')
    for a in cast['name']:
        casts.append(a)
    return casts

print(getcast('The Dark Knight'))

It says: File "C:.../Python/imdbtest.py", line 17, in getcast for a in cast['name']:

TypeError: string indices must be integers

greg-449
  • 109,219
  • 232
  • 102
  • 145
justaname
  • 3
  • 2

2 Answers2

0

You have to consider that movie.get('casts') will return a list of Person objects, and not a dictionary with the 'name' key.

Another (minor) thing I notice is that you get the movieID of the first result and then fetch the movie again. This may be omitted using the ia.update method.

A working example (that still assumes a lot of things, like the fact that a search will give you at least one result):

#!/usr/bin/env python3

import sys

from imdb import IMDb
ia = IMDb()

def getmovieID(movie_name):
    movie = ia.search_movie(movie_name)[0] # a Movie instance.
    ia.update(movie)
    return movie

def getcast(movie_name):
    movie = getmovieID(movie_name)
    casts = []
    for person in movie.get('cast', []):
        casts.append(person['name'])
    return casts

print(getcast('The Dark Knight'))
Davide Alberani
  • 1,061
  • 1
  • 18
  • 28
0

Refactor your code.

from imdb import IMDb
ia = IMDb()


def getmovieID(movie_name):
    movie = ia.search_movie(movie_name)[0]
    get_movie = ia.get_movie(movie.movieID)
    return get_movie


def getcast(movie_name):
    movie = getmovieID(movie_name)
    casts_objects = movie.get('cast')
    casts = []
    for person in casts_objects:
        casts.append(person.get('name'))
    return casts

print(getcast('The Dark Knight'))
sandeshdaundkar
  • 883
  • 1
  • 7
  • 14