I am trying to use key=operator.itemgetter()
to sort a field of data. When I try to customize it for the 4th column it doesn't sort correctly. Here are the first sort and the result.
import csv import operator
with open('test.csv', 'r', ) as test_file:
test_reader = csv.reader(test_file, delimiter=',')
list = sorted(test_reader, key=operator.itemgetter(0))
for row in list:
print(" ".join(row))
This is the output I get with the ID field sorted correctly
1009453, Lenovo, tower, 599, 10/1/2020,
1167234, Apple, phone, 534, 2/1/2021,
2347800, Apple, laptop, 999, 7/3/2020,
2390112, Dell, laptop, 799, 7/2/2020,
3001265, Samsung, phone, 1200, 12/1/2023,
7346234, Lenovo, laptop, 239, 9/1/2020, damaged
9034210, Dell, tower, 345, 5/27/2020,
But when I try to sort by price:
3001265, Samsung, phone, 1200, 12/1/2023,
7346234, Lenovo, laptop, 239, 9/1/2020, damaged
9034210, Dell, tower, 345, 5/27/2020,
1167234, Apple, phone, 534, 2/1/2021,
1009453, Lenovo, tower, 599, 10/1/2020,
2390112, Dell, laptop, 799, 7/2/2020,
2347800, Apple, laptop, 999, 7/3/2020,
The price here goes from 1200 down to 239 then up to 345, why isn't it sorting correctly? All I am changing for get a sorted price is this list = sorted(test_reader, key=operator.itemgetter(0))
to this list = sorted(test_reader, key=operator.itemgetter(3))
. The same happens when I try to sort by the date or key=operator.itemgetter(4))
the dates wouldn't be in chronological order.