pythonimdbpy

How to get name from movie.get('casts') function


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


Solution

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