Implementing Case Insensitive CSV Dictreader in Python

Case sensitivity is a common problem being faced by the developers while fetching data from a CSV file using CSV DictReader from a python dictionary

Implementing Case Insensitive CSV Dictreader in Python

Micropyramid

Case sensitivity is one of the common problems being faced by developers when you fetch data from a python dictionary. This will be a major problem especially when you read data from a CSV file using CSV DictReader. Here is the solution for this issue.

In general use cases, we upload the CSV files to the system to store huge amount of data by uploading single file. For example, in e-commerce sites we just write thousands of products details in a CSV file and just upload it.

In python, we can read the data of a CSV file in 2 ways. One by using normal csv.reader and the other by using CSV.DictReader. To learn more about CSV“s normal reader and dictreader check https://docs.python.org/2/library/csv.html

For More Deatils: https://bit.ly/2Sd8A1x

Why go for Case Insensitive CSV DictReader?

Using CSV reader we can read data by using column indexes and with DictReader we can read the data by using column names. Using the normal reader if the column indexes change then the data extraction goes wrong, to over come this we“ll go for DictReder. With DictReader we can read the data using column names.

Example CSV file format of products.csv:

TitleUPCCostSamsung GalaxySAM-12320,000MotoG2MOT-12311,000

With the following snippet we can read the above CSV file with DictReader.

import csv

with open(‚products.csv‘) as csvfile:

reader = csv.DictReader(csvfile)

for row in reader:

print(row[‚Title‘], row[‚UPC‘])

The above snippet will print title and upc details of the product. But there is a disadvantage of this if the row headers are gone wrong in terms of case sensitivity it will raise an error.

For ex: If Title is written as TITLE or „Title “ the above snippet raise KeyError.

To overcome above problem we have to make the DictReader case insensitive. For this, we have to override the CSV“s DictReader.

Source: https://micropyramid.com/blog/how-to-implement-case-insensitive-csv-dictreader-in-python/

Contact Us:

Micropyramid

Email: rahul@micropyramid.com

Website: https://micropyramid.com

Micropyramid a One stop tech shop to develop end-to-end custom web applications, mobile applications, devops and salesforce for StartUps and SME. I came across your profile on LinkedIn and believe you are the right person to reach out with this proposition

Kontakt
Micropyramid
Rahul Prem Kumar
Hyderabad 125
500038 Telangana
919182088035
rahul@micropyramid.com
https://micropyramid.com/