Read CSV Files using csv.DictReader in Python

To read CSV files in Python, we can use the csv.DictReader class from the built-in csv module. The DictReader reads each row into an ordered dictionary where the keys correspond to the column headers, making data retrieval easier using dictionary operations.


Examples to Read CSV Files

1. Reading a CSV File and Printing Each Row as a Dictionary

In this example, we will read a CSV file containing student records and print each row as a dictionary.

CSV File (students.csv):

main.py

</>
Copy
import csv

# Opening the CSV file
with open("students.csv", mode="r") as file:
    reader = csv.DictReader(file)  # Using DictReader

    # Reading each row and printing as a dictionary
    for row in reader:
        print(row)

Explanation:

  1. We open the CSV file in read mode using open() with the filename students.csv.
  2. We create a csv.DictReader object, which automatically maps column headers to dictionary keys.
  3. We iterate through each row using a for loop and print it as a dictionary.

Output:

{'Name': 'Arjun', 'Age': '20', 'Grade': 'A'}
{'Name': 'Ram', 'Age': '24', 'Grade': 'A'}
{'Name': 'Johny', 'Age': '20', 'Grade': 'B'}
{'Name': 'Priya', 'Age': '22', 'Grade': 'A'}

2. Reading Specific Columns from a CSV File

In this example, we will extract only the student names and grades from the CSV file.

main.py

</>
Copy
import csv

# Opening the CSV file
with open("students.csv", mode="r") as file:
    reader = csv.DictReader(file)

    # Extracting specific columns
    for row in reader:
        print(f"Name: {row['Name']}, Grade: {row['Grade']}")

Explanation:

  1. We open the file using open() in read mode.
  2. We create a csv.DictReader object.
  3. We iterate over each row and access specific columns using dictionary keys row['Name'] and row['Grade'].
  4. We print the extracted values using an f-string.

Output:

Name: Arjun, Grade: A
Name: Ram, Grade: A
Name: Johny, Grade: B
Name: Priya, Grade: A

3. Converting CSV Data into a List of Dictionaries

In this example, we will store the CSV data in a list of dictionaries for further processing.

</>
Copy
import csv

# Opening the CSV file
with open("students.csv", mode="r") as file:
    reader = csv.DictReader(file)

    # Converting CSV data into a list of dictionaries
    students = list(reader)

# Printing the list of dictionaries
print(students)

Explanation:

  1. We open the CSV file using open() in read mode.
  2. We create a csv.DictReader object.
  3. We convert the entire CSV data into a list of dictionaries using list(reader).
  4. We print the resulting list to see all the data at once.

Output:

4. Filtering Data Based on a Condition

In this example, we will filter students who have an A grade.

main.py

</>
Copy
import csv

# Opening the CSV file
with open("students.csv", mode="r") as file:
    reader = csv.DictReader(file)

    # Filtering students with grade 'A'
    high_achievers = [row for row in reader if row['Grade'] == 'A']

# Printing filtered data
print(high_achievers)

Explanation:

  1. We open the CSV file using open() in read mode.
  2. We create a csv.DictReader object.
  3. We use list comprehension to filter rows where the Grade column is ‘A’.
  4. We store the filtered rows in the high_achievers list and print it.

Output:

Conclusion

Using csv.DictReader, we can efficiently read CSV files into dictionaries, making data manipulation easier in Python.