Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Load CSV data into List and Dictionary using Python
CSV (Comma-Separated Values) files are widely used for data exchange between applications. Python's built-in csv module makes it easy to read CSV data into lists and dictionaries for further processing and analysis.
This article demonstrates how to load CSV data into Python's most commonly used data structures with practical examples.
Sample CSV Data
For our examples, we'll use a sample CSV file with the following data ?
Name,Age,Country Alice,25,USA Bob,30,UK Charlie,35,Canada
Loading CSV Data into a List
The csv.reader() function reads CSV data and converts it into a list of lists, where each sub-list represents a row ?
import csv
import io
# Sample CSV data as string (simulating file content)
csv_data = """Name,Age,Country
Alice,25,USA
Bob,30,UK
Charlie,35,Canada"""
# Using StringIO to simulate reading from a file
csv_file = io.StringIO(csv_data)
reader = csv.reader(csv_file)
data_list = list(reader)
print("CSV data as list:")
for row in data_list:
print(row)
CSV data as list: ['Name', 'Age', 'Country'] ['Alice', '25', 'USA'] ['Bob', '30', 'UK'] ['Charlie', '35', 'Canada']
Separating Headers and Data
You can separate headers from the actual data for easier processing ?
import csv
import io
csv_data = """Name,Age,Country
Alice,25,USA
Bob,30,UK
Charlie,35,Canada"""
csv_file = io.StringIO(csv_data)
reader = csv.reader(csv_file)
data_list = list(reader)
headers = data_list[0]
rows = data_list[1:]
print("Headers:", headers)
print("Data rows:")
for row in rows:
print(row)
Headers: ['Name', 'Age', 'Country'] Data rows: ['Alice', '25', 'USA'] ['Bob', '30', 'UK'] ['Charlie', '35', 'Canada']
Loading CSV Data into a Dictionary
The csv.DictReader() function creates a dictionary for each row, using the first row as column headers ?
import csv
import io
csv_data = """Name,Age,Country
Alice,25,USA
Bob,30,UK
Charlie,35,Canada"""
csv_file = io.StringIO(csv_data)
reader = csv.DictReader(csv_file)
data_dict = [row for row in reader]
print("CSV data as list of dictionaries:")
for person in data_dict:
print(person)
CSV data as list of dictionaries:
{'Name': 'Alice', 'Age': '25', 'Country': 'USA'}
{'Name': 'Bob', 'Age': '30', 'Country': 'UK'}
{'Name': 'Charlie', 'Age': '35', 'Country': 'Canada'}
Accessing Dictionary Data
With dictionary format, you can easily access specific values using column names ?
import csv
import io
csv_data = """Name,Age,Country
Alice,25,USA
Bob,30,UK
Charlie,35,Canada"""
csv_file = io.StringIO(csv_data)
reader = csv.DictReader(csv_file)
data_dict = [row for row in reader]
# Access specific person's data
print("Second person's country:", data_dict[1]['Country'])
print("All names:")
for person in data_dict:
print(f" {person['Name']}")
Second person's country: UK All names: ? Alice ? Bob ? Charlie
Comparison of Approaches
| Method | Data Structure | Access Method | Best For |
|---|---|---|---|
csv.reader() |
List of lists | Index-based | Simple data, positional access |
csv.DictReader() |
List of dictionaries | Key-based | Named columns, readable code |
Real File Example
When working with actual CSV files, replace the StringIO simulation with file operations ?
import csv
# Reading into list
with open('data.csv', 'r') as file:
reader = csv.reader(file)
data_list = list(reader)
# Reading into dictionary
with open('data.csv', 'r') as file:
reader = csv.DictReader(file)
data_dict = [row for row in reader]
Conclusion
Use csv.reader() for simple list-based storage when you need positional access. Use csv.DictReader() for more readable, key-based access to your CSV data. Both methods provide efficient ways to work with CSV files in Python.
