I want to sort the every row of the CSV string with the following code
import csv
def sort_csv_columns(csv_string: str) -> str:
# Split the CSV string into lines
lines = csv_string.strip().split("\n")
# Split the first line (column names) and sort it case-insensitively
header = lines[0].split(",")
header.sort(key=str.lower)
# Split the remaining lines (data rows) and sort them by the sorted header
data = [line.split(",") for line in lines[1:]]
data.sort(key=lambda row: [row[header.index(col)] for col in header])
# Join the sorted data and header into a single CSV string
sorted_csv = "\n".join([",".join(header)] + [",".join(row) for row in data])
return sorted_csv
# Test the function
csv_string = "Beth,Charles,Danielle,Adam,Eric\n17945,10091,10088,3907,10132\n2,12,13,48,11"
sorted_csv = sort_csv_columns(csv_string)
print(sorted_csv)
Output
Adam,Beth,Charles,Danielle,Eric
17945,10091,10088,3907,10132
2,12,13,48,11
Expected Output
Adam,Beth,Charles,Danielle,Eric\n
3907,17945,10091,10088,10132\n
48,2,12,13,11
What am I doing wrong
I am not able to sort the row besides the top header