user17046526
user17046526

Reputation:

Program should read from a file and returns a dictionary but returning a type error

The dataset looks like this-

Action|10|Golden Tree (2012)
Drama|3|Titanic (1967) 

So it is Genre|SerialNo|Movie

Required output is-

{ "Toy Story (1995)" : "Adventure", "Golden Tree (2012)" : "Action" }

Currently, the only output generated is "Action", I tried to write some code to fix it, but returns a type error. How do I fix this?

from collections import defaultdict

def read_genre_data(file):  
    movie_genre_dict  = {}
    ratings = defaultdict(list)
    for line in open(file):
        genre, num, movie  = line.split('|')
        #movie[genre].append(movie)   
    return genre
readGenre = read_genre_data("genreMovieSample.txt")
print(readGenre)

Upvotes: 0

Views: 33

Answers (1)

Barmar
Barmar

Reputation: 781848

You need to add to the dictionary, and then return the dictionary. You're just returning the value of genre from the last line of the file.

def read_genre_data(file):  
    movie_genre_dict  = {}
    with open(file) as f:
        for line in f:
            genre, num, movie  = line.split('|')
            movie_genre_dict[movie] = genre
        return movie_genre_dict

Upvotes: 1

Related Questions