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:

import csv
from collections import OrderedDict

kids = OrderedDict()
_name = 0
_age = 1

with open('kidsList.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile, fieldnames=("Id",),restkey="data_list")
        for row in reader:
            kids[row["Id"]] = row["data_list"]

print(f"ID = A1 has data: name= {kids['A1'][_name]}, age= {kids['A1'][_age]} ")

# Expected Output:
# ID = A1 has data: name= Alice, age= 6
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement