In this post, I am giving some examples of Python DictReader method to read the CSV files. For the following examples, I am using the customers.csv file, and the contents of the CSV is as below.
FIRST_NAME,LAST_NAME,PHONE_NUMBER,JOB_ID John,Erns,515.123.4568,AD_VP Lex,De Haan,515.123.4569,AD_VP Alexander,Hunold,590.423.4567,IT_PROG Bruce,Ernst,590.423.4568,IT_PROG
Read CSV File Contents Using DictReader in Python
In the following Python program example, it will read the CSV file and print the contents on the screen.
import csv with open("customers.csv", "r") as csv_file: csv_reader = csv.DictReader(csv_file, delimiter=',') for lines in csv_reader: print(lines)
Output
OrderedDict([('FIRST_NAME', 'John'), ('LAST_NAME', 'Erns'), ('PHONE_NUMBER', '515.123.4568'), ('JOB_ID', 'AD_VP')]) OrderedDict([('FIRST_NAME', 'Lex'), ('LAST_NAME', 'De Haan'), ('PHONE_NUMBER', '515.123.4569'), ('JOB_ID', 'AD_VP')]) OrderedDict([('FIRST_NAME', 'Alexander'), ('LAST_NAME', 'Hunold'), ('PHONE_NUMBER', '590.423.4567'), ('JOB_ID', 'IT_PROG')]) OrderedDict([('FIRST_NAME', 'Bruce'), ('LAST_NAME', 'Ernst'), ('PHONE_NUMBER', '590.423.4568'), ('JOB_ID', 'IT_PROG')])
Access Columns Through First Header Line of CSV Using DictReader
In the following example, it will read and print the first name, last name and job id by using the header row of the CSV file.
import csv with open("customers.csv", "r") as csv_file: csv_reader = csv.DictReader(csv_file, delimiter=',') for lines in csv_reader: print(lines['FIRST_NAME'], lines['LAST_NAME'], lines['JOB_ID'])
Output
John Erns AD_VP Lex De Haan AD_VP Alexander Hunold IT_PROG Bruce Ernst IT_PROG
Using the FIELDNAMES Clause in DictReader Method
In the below example, it will create the fields list in the columns list variable and then will print the first three columns.
import csv with open("customers.csv", "r") as csv_file: columns = ['FIRST_NAME', 'LAST_NAME', 'PHONE_NUMBER'] csv_reader = csv.DictReader(csv_file, fieldnames=columns, delimiter=',') for lines in csv_reader: print(lines['FIRST_NAME'], lines['LAST_NAME'], lines['PHONE_NUMBER'])
Output
FIRST_NAME LAST_NAME PHONE_NUMBER John Erns 515.123.4568 Lex De Haan 515.123.4569 Alexander Hunold 590.423.4567 Bruce Ernst 590.423.4568
You can notice, that the above program also prints the header row, which you can skip as shown in the following example:
import csv with open("customers.csv", "r") as csv_file: columns = ['FIRST_NAME', 'LAST_NAME', 'PHONE_NUMBER'] csv_reader = csv.DictReader(csv_file, fieldnames=columns, delimiter=',') next(csv_reader) for lines in csv_reader: print(lines['FIRST_NAME'], lines['LAST_NAME'], lines['PHONE_NUMBER'])
Output
John Erns 515.123.4568 Lex De Haan 515.123.4569 Alexander Hunold 590.423.4567 Bruce Ernst 590.423.4568