Converting CSV data into Python dictionaries is a common task, as dictionaries provide a flexible and efficient way to work with structured data. This section will explore the process of extracting data from CSV files and storing it in dictionaries.
Converting CSV to Dictionaries
To convert CSV data into dictionaries, you can use the csv.DictReader
class provided by the csv
module. This class reads the CSV file and returns an iterator that produces a dictionary for each row, where the keys are the column headers and the values are the corresponding data.
import csv
## Sample CSV data
with open('data.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
print(row)
The output of the above code will be a series of dictionaries, where each dictionary represents a row from the CSV file.
{'Name': 'John', 'Age': '25', 'City': 'New York'}
{'Name': 'Jane', 'Age': '30', 'City': 'London'}
Handling Header Rows
The csv.DictReader
class assumes that the first row of the CSV file contains the column headers. If this is not the case, you can specify the fieldnames manually when creating the DictReader
object.
import csv
## CSV file with no header row
with open('data.csv', 'r') as file:
reader = csv.DictReader(file, fieldnames=['Name', 'Age', 'City'])
for row in reader:
print(row)
This will produce the same output as the previous example, but without relying on the first row of the CSV file to contain the column headers.
Accessing Dictionary Values
Once you have converted the CSV data into dictionaries, you can easily access the values for each column by using the corresponding keys.
import csv
with open('data.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
name = row['Name']
age = row['Age']
city = row['City']
print(f"Name: {name}, Age: {age}, City: {city}")
This will output the individual values for each row in the CSV file.
By understanding how to convert CSV data into dictionaries, you can unlock the power of Python's data structures and perform more advanced operations on your CSV data.