Home > Mobile >  How to do something like 'index(match)' on parallel output
How to do something like 'index(match)' on parallel output

Time:09-27

My apologies if I seem stupid. I tried googling and searching but maybe I cannot formulate the right sentences because I cannot exactly get what I want out of it.

I have a CSV table

A   B   C
AA  BA  CA
AB  BB  CB
AC  BC  CC

I want to make it so that I input "AB" and Python will return data from BOTH Column A and Column B(AB is BB).

Anyone can show a sample code for me, please?

CodePudding user response:

Our sample CSV file:

with open('test.csv','w',newline='') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow(['A','B','C'])
    csvwriter.writerow(['AA','BA','CA'])
    csvwriter.writerow(['AB','BB','CB'])
    csvwriter.writerow(['AC','BC','CC'])

A simple way of getting what you need, is to turn it into a dictionary when you read it, this way you can simply use column headers to access your data:

with open('test.csv', newline= '') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if row['A'] == 'AB':
            print(row['A'],row['B'])

Without knowing more, it is difficult to provide more guidance.

  • Related