Reading CSV Files In Python By Using Inbuilt Modules (DictReader Function)

by Devansh


Posted on 16 Dec 2018 06:12:00 (3 months ago)




So in previous post I have shown you the first inbuilt method i.e. reader function. Now we will use the second Python inbuilt function to read the csv files i.e. DictReader function. So, I am using again the same data i.e. 'person.csv' which contains the below data,

Name,Place,Date
Sam,New York,23102015
Juli,Cape Town,12122017
Avinash,New Delhi,09122016
Rio,Tokio,01072015

So incase of DictReader function, this function parse each row in ordered dictionaries with key value pair. So below is the code to use DictReader function.

from csv import DictReader

with open('person.csv') as file:
    data = DictReader(file)
    for row in data:
    	print(row)

So after running the above code you will get the ouput like this,

OrderedDict([('Name', 'Sam'), ('Place', 'New York'), ('Date', '23102015')])
OrderedDict([('Name', 'Juli'), ('Place', 'Cape Town'), ('Date', '12122017')])
OrderedDict([('Name', 'Avinash'), ('Place', 'New Delhi'), ('Date', '09122016')])
OrderedDict([('Name', 'Rio'), ('Place', 'Tokio'), ('Date', '01072015')])