Python Forum

Full Version: csv filtering with python.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
One last thing, the output produced :
Output:
04X-1101-0116,1633-0001
04X-1101-0114,1633-0002
04X-1101-0112,1633-0021
04X-1101-0113,1633-0050
04X-1101-0115,1633-0020

How would you go about sorting this by he 2nd column? ie serial number. ?? would it be a sort() function?
def filter_csv(csv_file):
    reader = csv.DictReader(csv_file)
    dedup_data = list({(row['part_number'], row['product_serial_number']) for row in reader})
    return sorted(dedup_data, key=lambda item:item[1])
Sorting HOW TO

and yes, .sort method would also do, but you need to use it on separate line
def filter_csv(csv_file):
    reader = csv.DictReader(csv_file)
    dedup_data = list({(row['part_number'], row['product_serial_number']) for row in reader})
    dedup_data.sort(key=lambda item:item[1])
    return dedup_data
Note that according to docs, .sort() method is slightly more efficient than sorted function:
Quote:You can also use the list.sort() method. It modifies the list in-place (and returns None to avoid confusion). Usually it’s less convenient than sorted() - but if you don’t need the original list, it’s slightly more efficient.
thanks, i had missed the correct formatting of the sort ( bla bla).
Pages: 1 2