Help on For Loop!


#1
my_file = open('books.csv', 'r')
one_value = []
value = []
for i in range(0, 4):
    for each_line in my_file:
        line_list = each_line.strip('\n').split(',')
        one_value.append(line_list[i])
        value.append(one_value)
    one_value = []
print(value)

books.csv is a file like:

 book.title,book.year,book.author
 Godel Escher Bach, 1979, Douglas Hofstadter
 What if?, 2014, Randall Munroe

What i want to do is take the items with same index in the each line into a list and build another list with each item is the list contains items with same index in each line.

The output should be:

['[booktitle','Godel Escher Bach','What if?'],[,'book.year', '1979', '2014',],['book.autho'r, 'Douglas Hofstadter', 'Randall Munroe']]

But there seems some errors in my loop and what i actually get is:

[['book.title', 'Godel Escher Bach', 'What if?'],['book.title', 'Godel Escher Bach', 'What if?'] ['book.title', 'Godel Escher Bach', 'What if?']]

Help please.


#2

Your best bet would to actually create a dictionary for this data, it is more appropriate than lists of lists.

EXAMPLE:

# The key is the title of the book, or we can create a dict in a dict with title as the key
# It really is up to you as the programmer.
books = {'Godel Escher Bach': {'year': 1979, 'author': 'Douglas Hofstadter'}}
books['Godel Escher Bach'].items()
books['Godel Escher Bach']['year']

That's how you would access the data.

As for assigning the data you would do something like,

Also because we know the data structure we know right where each entry should be.

def get_book_data(bookfile):
    with open(bookfile as 'r') as file:
        book_dict = dict()
        for line in file:
            hold = line.split(",")
            book_dict[hold[0]] = {'year': int(hold[1]), 'author': hold[2]}
    return book_dict

books = get_book_data('books.csv')
# Now we have the book data in a dict which allows us to easily access the information is a useful way.
books
# OUTPUT: {'Godel Escher Bach': {'year': 1979, 'author': ' Douglas Hofstadter'}}

Now that your book data is stored in a dict you can easily convert it back to a csv file or even save the dict directly and load the data that way.

Also even though dicts are typically unordered you can use several built-in tools to order the dicts.

# Sample
from collections import OrderedDict

This part of collections allows you do do all kindsa fun things with dicts.

You use it like following

OrderedDict(sorted(books.items()))

Any questions, ask freely.


#3

Total aside... Can't help but notice the book, itself. A discovery of the meaning of meaning. Idiom, or literal?