4 ms·
I thought the Go code looked way too complex and Python would be simpler. Yes and no. import csv filename = 'example.csv' sort_by = 'index' reverse
by gabrielsroka 4y ago
I thought the Go code looked way too complex and Python would be simpler. Yes and no.
import csv
filename = 'example.csv'
sort_by = 'index'
reverse = True
with open(filename) as f:
lines = [d for d in csv.DictReader(f)]
for line in lines:
line['index'] = int(line['index'])
lines.sort(key=lambda line: line[sort_by], reverse=reverse)
print(','.join(lines[0].keys()))
for line in lines:
print(','.join(str(v) for v in line.values()))
- deleted 4y ago[deleted]
- cmdlineluser 4y agoPerhaps a `DictWriter` would simplify things: import csv import sys filename = "example.csv" sort_by = "index" reverse = True with open(filename, newline="") as f: reader = csv.DictReader(f) writer = csv.DictWriter(sys.stdout, fieldnames=reader.fieldnames) writer.writeheader() writer.writerows(sorted(reader, key=lambda row: int(row[sort_by]), reverse=reverse))
- gabrielsroka 4y agoI thought about that but 1) it seemed like cheating to write to standard out, 2) you're assuming that the column to sort by is an integer whereas I broke that code up a little bit. But yours has the advantage of being able to support more complex CSVs.