pythonlistsortingcsvnumerical

how do i sort data from a csv file numerically in python


I am writing a program that takes students scores from a csv file and needs to sort then highest to lowest score. the csv file looks like this:

josh 12
john 6
fred 8
harry 7

i have tried to put the items in a list like this:

 Mylist=[]
csvfile = open (classname,'r')
reader = csv.reader(csvfile)
for row in reader:
    Mylist.append(row)

then reverse the list to put the numerical value first:

Mynewlist = []
    for each in Mylist:
        value2 = ''.join(each[0])
        value1 = ''.join(each[1])
        mynewlist.append(value1,value2)

with no luck i get this error:

    Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    main()
  File "\\SRV-FILE3\ca231$\task 3\3.py", line 143, in main
    value1 = ''.join(each[1])
IndexError: list index out of range

i use ''.join(each[1]) to convert to a string and then append them in the opposite order then i planned to use .sort() to sort them numerically but I cant get them to append to a list.

does anyone know how to sort the contents of a csv file by its numerical value?


Solution

  • I think you're overcomplicating things. Assuming you have the data as a list of lists:

    data = [("josh", "12"), ("john", "6"), ("fred", "8"), ("harry", "7")]
    

    This could come from CSV of course, it doesn't matter to the sorting. You can sort just by calling sorted():

    sorted(data, key = lambda x: int(x[1]))
    

    The lambda is a function that picks the second element of each sub-list as the key, i.e. the score, and converts it to a number for sorting. This prints:

    [('john', '6'), ('harry', '7'), ('fred', '8'), ('josh', '12')]