0

I am totally lost as to why I keep getting errors. I am trying to print the titles of the books listed in alphabetical order using sorted().

I keep getting this error:

sorted(BSI, key=list(Book))
TypeError: 'type' object is not iterable

Then this is the code

from collections import namedtuple

Book = namedtuple('Book', 'author title genre year price instock')
BSI = [Book("J.K. Rowling", "Harry Potter", "Fantasy", "2005", 12.00, "34"),
       Book("Dr. Seuss", "Green Eggs and Ham", "Children's", "2000", 8.00, "12"),
       Book("Margaret Mitchell", "Gone with the Wind", "Fiction", "1980", 9.00, "30"),
       Book("John Green", "The Fault in our Stars", "Fiction", "2010", 13.00, "23"),
       Book("Stephanie Meyer", "Twilight", "Fantasy", "2008", 15.00, "8"),
       Book("Suzanne Collins", "The Hunger Games", "Fantasy", "2005", 17.00, "18")]

for x in BSI:
    print(x.title)

y = BSI
for x in BSI:
    sorted(BSI, key=list(Book))
Georgy
  • 12,464
  • 7
  • 65
  • 73
  • Does this answer your question? [Pythonic way to sorting list of namedtuples by field name](https://stackoverflow.com/questions/12087905/pythonic-way-to-sorting-list-of-namedtuples-by-field-name) – Georgy Mar 22 '20 at 16:10

1 Answers1

1

The problem is with list(Book). Book is a type. The following might be what you want.

from collections import namedtuple

Book = namedtuple('Book', 'author title genre year price instock')

BSI = [
    Book ("J.K. Rowling", "Harry Potter", "Fantasy", "2005", 12.00 ,     "34"),
    Book ("Dr. Seuss", "Green Eggs and Ham", "Children's", "2000", 8.00 , "12"),
    Book ("Margaret Mitchell", "Gone with the Wind", "Fiction", "1980", 9.00, "30"),
    Book ("John Green", "The Fault in our Stars", "Fiction", "2010", 13.00, "23"),
    Book ("Stephanie Meyer", "Twilight", "Fantasy", "2008", 15.00, "8"),
    Book ("Suzanne Collins", "The Hunger Games", "Fantasy", "2005", 17.00, "18"),
    ]

for x in BSI:
    print (x.title)
print()
for x in sorted(BSI, key=lambda x: x.title):
    print(x.title)

You can elaborate the key if you really think you might have duplicate titles.

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52