I'm assuming that given a csv file of user names and quiz scores, you want to read the csv file and then sort based on user names. Your problem (I believe) is that each time you read from the csv file, you get a list of the form [user_name, score1, score2, score3]
.
If so, why not store each such list in a dictionary, using the user_names as keys, and then sort the dictionary keys - i.e.
sorting_dict = {}
for curr_elem in readCSV:
sorting_dict[curr_elem[0]] = curr_elem #Note this assumes no 2 users have the same name
sorted_names = sorted(sorting_dict.keys()) # actually sorted(sorting_dict) will also work and may be preferred, but '.keys()' makes it clearer for me
Now, you can access your records in sorted order:
for curr_user in sorted_names:
curr_record = sorting_dict[curr_user]
#Do what you want from here...
====================================================
Hmmmmm... it's odd this didn't work for you. I made a dummy file like you described and this is what seemed to work for me:
>>> f=open('csv.txt','r')
>>> readCSV = csv.reader(f)
>>> for curr_elem in readCSV:
... sorting_dict[curr_elem[0]] = curr_elem
...
>>> sorted_names = sorted(sorting_dict.keys())
>>> sorted_names
['art', 'bob', 'dick', 'harry', 'tom']
>>> for curr_user in sorted_names:
... print sorting_dict[curr_user]
...
['art', '77', '99', '98']
['bob', ' 88', '99', '78']
['dick', '77', '66', '99']
['harry', '90', '78', '98']
['tom', '33', '98', '67']
>>>
where my csv.txt file was:
bob, 88,99,78
art,77,99,98
tom,33,98,67
dick,77,66,99
harry,90,78,98
the only 'gotcha' here is you need to be sure the 'harry' line doesn't end with a \n
, otherwise the csv reader will read an empty line that will throw an error at sorting_dict[curr_elem[0]] = curr_elem
, but one can easily guard against that.