Python

How to Use Python Csv Dictreader

The DictReader () is used to read the file of the csv in the format of the dict object. Let’s discuss how to use the DictReader () method in python.

Before we start the main course of this article, let’s first understand what a csv file is.

What is a CSV (Comma Seperated Values) File?:

A CSV is a file in which data is in the form of a comma-separated or other delimiter user choice separated. These files have extension csv. This csv file is mostly used in data analytics. Apart from the data analytics, the csv file is also used in the e-commerce application because it’s very easy to handle in all different programming languages.

1. DictReader () method to read particular column name:

CSV file: The below is a test.csv file. This csv file we will be read from the DictReader(). In this program, we are not going to read the whole csv file data instead only the Month column as shown in the below:

"Month", "1958", "1959", "1960"

"JAN",  340,  360,  417

"FEB",  318,  342,  391

"MAR",  362,  406,  419

"APR",  348,  396,  461

"MAY",  363,  420,  472

"JUN",  435,  472,  535

"JUL",  491,  548,  622

"AUG",  505,  559,  606

"SEP",  404,  463,  508

"OCT",  359,  407,  461

"NOV",  310,  362,  390

"DEC",  337,  405,  432

Python code:

1
2
3
4
5
6
7
8
9
import csv

with open('test.csv') as f:

    DictReader_obj = csv.DictReader(f)

    for item in DictReader_obj:

        print(item['Month'])

Output:

JAN

FEB

MAR

APR

MAY

JUN

JUL

AUG

SEP

OCT

NOV

DEC

Line 1: We import the csv module.

Line 2 to 5: We open the test.csv file as f, and then we create an object of the DictReader. The object (DictReader_obj) then displays all the data of the column Month.

2. DictReader () method to read csv file as a dictionary:

Now, we are going to see how we can read the csv as a dictionary format. We are using the same test.csv file as we used before. The example for this method is given below:

1
2
3
4
5
6
7
8
9
import csv

with open('test.csv') as f:

    DictReader_obj = csv.DictReader(f)

    for item in DictReader_obj:

        print(dict(item))

Output:

{'Month': 'JAN', ' "1958"': '  340', ' "1959"': '  360', ' "1960"': '  417'}

{'Month': 'FEB', ' "1958"': '  318', ' "1959"': '  342', ' "1960"': '  391'}

{'Month': 'MAR', ' "1958"': '  362', ' "1959"': '  406', ' "1960"': '  419'}

{'Month': 'APR', ' "1958"': '  348', ' "1959"': '  396', ' "1960"': '  461'}

{'Month': 'MAY', ' "1958"': '  363', ' "1959"': '  420', ' "1960"': '  472'}

{'Month': 'JUN', ' "1958"': '  435', ' "1959"': '  472', ' "1960"': '  535'}

{'Month': 'JUL', ' "1958"': '  491', ' "1959"': '  548', ' "1960"': '  622'}

{'Month': 'AUG', ' "1958"': '  505', ' "1959"': '  559', ' "1960"': '  606'}

{'Month': 'SEP', ' "1958"': '  404', ' "1959"': '  463', ' "1960"': '  508'}

{'Month': 'OCT', ' "1958"': '  359', ' "1959"': '  407', ' "1960"': '  461'}

{'Month': 'NOV', ' "1958"': '  310', ' "1959"': '  362', ' "1960"': '  390'}

{'Month': 'DEC', ' "1958"': '  337', ' "1959"': '  405', ' "1960"': '  432'}

Line 1: We import the csv module.

Line 2 to 5: We open the test.csv file as an f, and then we create an object of the DictReader. The object will continue to iterate till the data. The csv.DictReader() will return each row of type an OrederedDict, so we convert each OrderedDict type row to a dict using the type cast method. The object reader then displays all the data in the dictionary format, as shown in the above output.

But, if you are using the latest python, then dict type conversion is not required, as we are using type cast in line number 5 of the above program example.

3. DictWriter () method:

DictWriter method is a part of the DictReader method where it helps to write the dictionary format data to the csv file. So in this program, we will see how we can write the dictionary data to the csv.

1
2
3
4
5
6
7
8
9
10
11
import csv

with open('output.csv',"w", newline="", encoding="utf-8-sig") as outfile:

    writer = csv.DictWriter(outfile, ["FirstName", "LastName"])

    writer.writeheader()

    new_row = {"FirstName": "Linux", "LastName": "Hint"}

    writer.writerow(new_row)

Ouput:

FirstName,LastName

Linux,Hint

Line 3 to 7: We open the output.csv file in the writing mode (‘w’). Then we pass the header of the csv in the form of the list to the DictWriter while creating the object itself. We have to tell the column names of the csv to the object before writing to the csv; else, it will generate an error because then the object will not be able to understand the key names of the dictionary. In line 6, we created one dict object and passed it to the writerow object to write into the csv file.

The output shows that our data is successfully written on the csv file.

4. DictWriter () method to write a list of dictionary data to csv:

In this program, we will see how we can write a list of dictionary data to csv. In the previous example, we have written only single dictionary data to csv for understanding the concept. But we write csv with huge data in daily life. So we are going to see that scenario in this example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import csv

with open('output.csv', 'w') as csvfile:

    col = ['FirstName', 'LastName', 'GradePoint']

    writer = csv.DictWriter(csvfile, fieldnames=col)

    writer.writeheader()

    writer.writerows([{'GradePoint': 'B', 'FirstName': 'Jeorge', 'LastName': 'Belly'},

        {'GradePoint': 'A', 'FirstName': 'Krishna', 'LastName': 'Kumar'},

        {'GradePoint': 'C', 'FirstName': 'Sheon', 'LastName': 'Shaiyer'},

        {'GradePoint': 'B', 'FirstName': 'Janny', 'LastName': 'Jeus'},

        {'GradePoint': 'A', 'FirstName': 'Sham', 'LastName': 'Sharma'}])

Output:

FirstName,LastName,Grade

Jeorge,Belly,B

Krishna,Kumar,A

Sheon,Shaiyer,C

Janny,Jeus,B

Sham,Sharma,A

Line 3 to 11: We open the output.csv file in the writing mode (‘w’). Then we pass the header of the csv in the form of the list to the DictWriter while creating the object itself. We have to tell the column names of the csv to the object before writing to the csv; else, it will generate an error because then the object will not be able to understand the key names of the dictionary. In line 7, we created a list of dictionary objects and passed it to the writerows object to write all the data into the csv file at once.

The output shows that our data is successfully written on the csv file.

Conclusion: In this article, we have learned how to use the methods DictReader () and DictWriter (). We have also seen the way to write a list of dictionary objects to csv at once. The main difference when we write a list of dictionaries or a single dictionary object is method writerows. We used the writerows method when we had more than one data and the writerow when we had only single data.

About the author

Shekhar Pandey