Python: Creating a list of dicitionaries from lists in a text file. Please help!
ID: 3721072 • Letter: P
Question
Python: Creating a list of dicitionaries from lists in a text file.
Please help! I'm not sure how to do it and repeat the process.
So far this is the code I have:
But I'm not sure how to repeat this process to create the new list of dictionaries.
For action-romance, I need a boolean response.
The text file I'm using is located here: http://s000.tinyupload.com/?file_id=48953557772434487729
An example of what a dictionary should look like is this:
Thank you in advance for any help!
For example, from the dataset, the information of the first movie is: $ 1971 121 NR 001100 A dictionary below should be built for this movie: {"Title": "S", "Year": 1971, "Length": 121, "Rating": "NR", "Action": False, "Animation": False, "Comedy" True, "Drama": True, "Documentary" False, "Romance": False)Explanation / Answer
movies_list = []
dict1 = {}
file_ref = open("movies.txt", 'r')
line = file_ref.readline() #to skip first line with title headings
for line in file_ref:
movie_data = line.split(" ") #split line on the basis of tab
# add the movie if line contains the proper data with all 5 values
# array index start from 0.
if len(movie_data) == 5:
dict1["title"] = movie_data[0]
dict1["year"] = movie_data[1]
dict1["length"] = movie_data[2]
dict1["rating"] = movie_data[3]
dict1["action"] = movie_data[4][0] == 1
dict1["animation"] = movie_data[4][1] == 1
dict1["comedy"] = movie_data[4][2] == 1
dict1["drama"] = movie_data[4][3] == 1
dict1["documentary"] = movie_data[4][4] == 1
dict1["romance"] = movie_data[4][5] == 1
movies_list.append(dict1)
file_ref.close()
print(movies_list)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.