Reading CSV Files Into a Dictionary With csv
We can read a CSV file into a dictionary using the csv
module in Python and the csv.DictReader
class. Here’s an example:
Suppose, we have a employees.csv file and content inside it will be:
name,department,birthday_month
John Smith,HR,July
Alice Johnson,IT,October
Bob Williams,Finance,January
In this example, csv.DictReader
reads each row of the CSV file as a dictionary where the keys are the column headers, and the values are the corresponding values in each row. The dictionaries are then appended to a list (data_list
in this case).
Python3
import csv # Open the CSV file for reading with open ( 'employees.csv' , mode = 'r' ) as file : # Create a CSV reader with DictReader csv_reader = csv.DictReader( file ) # Initialize an empty list to store the dictionaries data_list = [] # Iterate through each row in the CSV file for row in csv_reader: # Append each row (as a dictionary) to the list data_list.append(row) # Print the list of dictionaries for data in data_list: print (data) |
Output:
{'name': 'John Smith', 'department': 'HR', 'birthday_month': 'July'}
{'name': 'Alice Johnson', 'department': 'IT', 'birthday_month': 'October'}
{'name': 'Bob Williams', 'department': 'Finance', 'birthday_month': 'January'}
Working with csv files in Python
Python is one of the important fields for data scientists and many programmers to handle a variety of data. CSV (Comma-Separated Values) is one of the prevalent and accessible file formats for storing and exchanging tabular data.
In article explains What is CSV. Working with CSV files in Python, Reading, and Writing to a CSV file, and Storing Emails in CSV files.
Table of Content
- What is a CSV File?
- Working with CSV files in Python
- Reading a CSV file
- Reading CSV Files Into a Dictionary With csv
- Writing to a CSV file
- Writing a dictionary to a CSV file
- Reading CSV Files With Pandas
- Writing CSV Files with Pandas
- Storing Emails in CSV files