Skip to content
Advertisement

Python 3-x Select a column and a row from a CSV table using SQL-like conditions

Here’s a CSV file kidsList.csv, comma-delimited, the first row is a header. The first column Id is unique so you can use this as a primary key.

Id,Name,Age
A1,Alice,6
A2,Becca,5
B1,Cindy,7

Now I want to find the name where Id is A2; the answer should be “Becca”.

In SQL it is like SELECT Name FROM table WHERE Id = "A2"

How can I do this in Python 3.x? This operation is so simple that I want to use the Standard Library like csv rather than non-standard ones like pandas.

Advertisement

Answer

I think the csv.DictReader class can be utilized to create a dictionary mapping that you can index by the value of the Id column:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement