0

I have a program to make a bookstore database, and I have used CSV to store my data, through using nested list with each list as an entry for a particular book. The fields are ["Book ID","Title","Genre","Author","Stock"], and in a function to tabulate the data (tabulate module used), I wanted to give the option to sort the data alphabetically using each entry's 2nd element ("Name").

This is my current function :-

def admin_showall():
    print("----------------------------------------\n")
    with open("Book_List.csv","r+") as f:
        all_data = csv.reader(f,delimiter=",")
        next(all_data)
        print("[All Books]\n")
        fields = ["Book ID","Title","Genre","Author","Stock"]
        print(tabulate(all_data,fields))
    print("\nSuccessfully displayed!")
    print("\nFilters to apply:")
    print("   [1] Sort By Name\n   [2] Sort by Genre\n   [3] Sort by Author\n   [4] Sort by Stock")
    ans = input("Enter your choice: ")
    if ans == "1":

It's incomplete, as I can't figure out how to sort the data. Could anyone give any suggestions?

  • You forgot to post your attempt at sorting the data. – Scott Hunter Sep 27 '22 at 13:01
  • And a clear reproducible input/output example – mozway Sep 27 '22 at 13:07
  • Does this answer your question? [How to sort a list/tuple of lists/tuples by the element at a given index?](https://stackoverflow.com/questions/3121979/how-to-sort-a-list-tuple-of-lists-tuples-by-the-element-at-a-given-index) – buran Sep 27 '22 at 13:32
  • The [`pandas`](https://pandas.pydata.org/) library is the reference for handling tabular data (such as `csv`). It will greatly ease simple operation such as sorting. – cbo Sep 29 '22 at 08:47

1 Answers1

0

That's pretty easy with

a = [[0, 'Beta', 3], [1, 'Alpha', 11], [7, 'Gamma', 5]]
b = sorted(a, key=lambda x: x[1])
print(b)
# [[1, 'Alpha', 11], [0, 'Beta', 3], [7, 'Gamma', 5]]