Print all rows related to the minimum values ​​of another column based on the distinct values ​​of a specific column in the csv file using python csv

advertisements

I have a CSV file with following structure:

Id,User,P_Name,P_Code,Rate

1,U1,P1,1234,21.5

2,U1,P2,7483,20

3,U1,P3,8945,29.5

4,U2,P1,1234,80

5,U2,P2,7483,23.5

6,U2,P3,8945,30

7,U3,P1,1234,15

8,U3,P2,7483,27.3

9,U3,P3,8945,,29.7

I want to print complete rows for minimum value of each product. For instance, here it would be:

7,U3,P1,1234,15

2,U1,P2,7483,20

3,U1,P3,8945,29.5

I am new to python and unable to proceed after this:

import csv
with open('sample.csv', 'rb') as csvfile:
        filereader = csv.reader(csvfile, delimiter=',', quotechar='|')
        headers=next(filereader)
        data = []
        for row in filereader:
                data.append(row[2])
        print (data)

Here, I am getting a list of P_Name values and unable to figure out how to get minimum value of each distinct product.


Thanks for the response. I had modified your code a bit to make it a bit simpler.

filter = {} for item in data: if item[2] not in filter.keys():
filter[item[2]] = item
elif item[4] == filter[item[2]][4]:
filter[item[2]].append(item) elif item[4] < filter[item[2]][4]:
filter[item[2]] = item

Although, it works fine. However, I am facing some issues with formatting of the result after updating row 5 (post header) in the csv file from

5,U2,P2,7483,23.5

to

5,U2,P2,7483,20

And then printed results using following code:

 for item in filter.keys():
                print filter[item]

Results are as follows:

['2', 'U1', 'P2', '7483', '20', ['5', 'U2', 'P2', '7483', '20']]
['3', 'U1', 'P3', '8945', '29.5']
['7', 'U3', 'P1', '1234', '15']

whereas if in case there are two users paying identical price for a particular product then instead of appending those details along with previous user, I want to display it as a separate entry and in similar format as csv file (without brackets and quotes), like:

2,U1,P2,7483,20
5,U2,P2,7483,20
3,U1,P3,8945,29.5
7,U3,P1,1234,15