Python Forum
Thread Rating:
  • 1 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
csv filtering with python.
#11
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?
Reply
#12
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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#13
thanks, i had missed the correct formatting of the sort ( bla bla).
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Unexpected Output - Python Dataframes: Filtering based on Overlapping Dates Xensor 5 654 Nov-15-2023, 06:54 PM
Last Post: deanhystad
  Help with filtering in Python Junes786 2 81,331 Jun-05-2019, 08:10 AM
Last Post: Junes786

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020