I have a text file where the information that is formated as
Title, Author, User Rating, Reviews, Price, Publication Year, Genre(Fiction or nonfiction)
sample data form txt
test_data = """
Girls,Hopscotch Girls,4.8,9737,7,2019,Non Fiction
I - Alex Cross,James Patterson,4.6,1320,7,2009,Fiction
If Animals Kissed Good Night,Ann Whitford Paul,4.8,16643,4,2019,Fiction
"""
They are all separated by a comma (,). I wanted to take this input and make it into a list that looks something like
list = {'Name': 'Girls','Author': 'Hopscotch Girls','User Rating':'4.8', 'Reviews':'9737', 'Price':'7', 'Publication Year':'2019', 'Genre':'Non Fiction'}
I'm trying to make it a list so its easier to look through because later on in my program since I want to be able to get user input like year and list all the books within the year with. It will also make formating an output easier.
CodePudding user response:
If you are reading the data from a .txt file
data = {'Name': [], 'Author': [], 'User Rating': [], 'Reviews': [], 'Price': [], 'Publication Year': [], 'Genre': []}
with open("filename/goes/here.txt", "r") as f:
for line in f.readlines():
lineData = line.split(r",")
for key, ld in zip(data.keys(), lineData):
data[key].append(ld)
From your description I believe this is a solution. Some advice, never name your variables with the same name as any built-in functions. (e.g. list, int, str)
CodePudding user response:
Given your requirement
I'm trying to make it a list so its easier to look through because later on in my program since I want to be able to get user input like year and list all the books within the year with. It will also make formating an output easier.
I think that a list of dictionaries would do the job. Using list comprehension (I am using the test_data you defined in the question):
tags = ["Name", "Author", "User Rating", "Reviews", "Price", "Publication Year", "Genre"]
result = [dict(zip(tags, x.split(","))) for x in test_data.split("\n") if len(x.strip()) > 0]