handle duplicate values separately in python

The name of the picture


handle duplicate values separately in python



I have a csv file which contains rows like below:


113,25CNFW,"test1",1ALNAU,25CNFW
113,25D5L2,"test2",1ALNAU,25D5L2
114,MCF82H,"test3",307531,MCF82H



Now, I'm trying to extract 2nd and 4th column of every row by searching certain nos in the 1st column, but whenever the 1st column contains duplicates, my script logic fails as it treats duplicates as single entry. Is there any way to iterate over duplicates in python such that each duplicate value is considered as individual?


import csv

mycsv = "/home/test.csv"

def csv_read(fobj, mid):
reader = csv.reader(fobj)
for row in reader:
if mid in row:
contid = row[1]
accid = row[3]
return accid,contid


list = ['113','114']
for mid in list:
with open(mycsv,"r") as fobj:
detail = csv_read(fobj,mid)
print detail[0] + "," + detail[1]



Output:


1ALNAU,25CNFW
307531,MCF82H

Process finished with exit code 0



So, in short I want 113 to be considered twice.



I've tried working around with different options, but they didn't work :(





Hi @optimus-prime. I tried your code and it worked fine for me after removing the return statement (since it's not a function). Also want to mention that you don't need the f.close() as the with statement provides code-control and closes the file for you automatically. You may also want to look at the pandas library which can be very helpful when working with tabular data.
– blazetopher
yesterday




return


f.close()


with





Hi @blazetopher. Thanks for looking into my issue and the tips. The reason I'm using 'return' is because I'm passing values of 'accid' and 'contid' to further part of my code in my script. I've edited the original code now along with the output what I'm getting. I think if this isn't working, I may have to look into pandas library as you suggested.
– Optimus Prime
5 mins ago









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Arduino Mega cannot recieve any sketches, stk500_recv() programmer is not responding

Visual Studio Code: How to configure includePath for better IntelliSense results

C++ virtual function: Base class function is called instead of derived