Reputation: 89
I have this csv file:
ID,Name,Score1,Score2,Score3
100,Anne,3,4,5
101,Frank,1,2,3
102,Shawn,7,8,9
103,Bo,3,6,5
104,James,4,7,2
I want to sort the csv file in an alphabetically order by their names, like this:
ID,Name,Score1,Score2,Score3
100,Anne,3,4,5
103,Bo,3,6,5
101,Frank,1,2,3
104,James,4,7,2
102,Shawn,7,8,9
So far I´ve tried this:
def alphabetically_ordered(file_name):
Wanted_order = {"A":0,"B":1,"C":2,"D":3,"E": 4,"F":5,"G":6,"H":7,"I":8,"J": 9,"K":10,"L":11,"M":12,"N":13,"O":14,"P":15,"Q":16,"R":17,"S":18,"T": 19,"U":20,"V":21,"W":22,"X":23,"Y": 24,"Z":25,"Æ":26,"Ø":27,"Å":28}
with open('file_name','rb') as f_input:
csv_input = csv.reader(f_input)
header = next(csv_input)
data = sorted(csv_input,key=lambda x: (Wanted_order[x[1]], socket.inet_aton(x[0])))
return data
But I get an Error message.
How do I sort my csv file alphabetically by the names?
Upvotes: 2
Views: 438
Reputation: 82765
Using just sorted
with lambda
function in key
should work.
Ex:
import csv
with open(filename, "rU") as f_input:
csv_input = csv.reader(f_input)
header = next(csv_input)
data = sorted(csv_input, key=lambda x: x[1])
print(data)
Output:
[['100', 'Anne', '3', '4', '5'], ['103', 'Bo', '3', '6', '5'], ['101', 'Frank', '1', '2', '3'], ['104', 'James', '4', '7', '2'], ['102', 'Shawn', '7', '8', '9']]
Edit as per comment
with open(filename, "wb") as f_input:
csv_out = csv.writer(f_input)
csv_out.writerow(header)
csv_out.writerows(data)
Upvotes: 4