How to sort a nested list through one of its elements?

Question:

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 Namen   [2] Sort by Genren   [3] Sort by Authorn   [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?

Asked By: Ishaan Ahmed

||

Answers:

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]]
Answered By: Vsevolod Timchenko
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.