how can I sort a bunch of lists over multiple fields?

Lonnie Princehouse finite.automaton at gmail.com
Wed Apr 27 16:39:15 EDT 2005


Might as well make a class for Book instead of dealing with buckets of
lists...

class Book(object):
    def __init__(self, title, author, publisher, isbn, date):    # add
more fields according to CSV
        self.__dict__.update(locals())  # lazy!
    def __repr__(self):
        return '<"%s" by %s>' % (self.title, self.author)

def read_books(filename):
    import csv   #   (this battery is included)
    csv_file = open(filename, "rb")
    reader = csv.reader(csv_file)
    books = [Book(*[field.strip() for field in row]) for row in reader]
    csv_file.close()
    return books

if __name__ == '__main__':
    books = read_books("my_csv_file.csv")
    import operator

    # example - Sort by author
    books.sort(key = operator.attrgetter("author"))
    
    for book in books:
        print book




More information about the Python-list mailing list