For more flexibility, you can use a dictionary to store data from the CSV file. This approach is especially helpful when you want to dynamically handle multiple rows or columns. Here’s an example:
import csv
# Initialize a dictionary to store data by rows
data = {'Dec': [], 'Jan': []}
# Open the CSV file
with open('data.csv', mode='r') as file:
reader = csv.DictReader(file) # Read rows as dictionaries
# Loop through each row
for row in reader:
data['Dec'].append(int(row['Dec:']))
data['Jan'].append(int(row['Jan:']))
# Calculate totals dynamically
total_dec = sum(data['Dec'])
total_jan = sum(data['Jan'])
print(f"Total for Dec column: {total_dec}")
print(f"Total for Jan column: {total_jan}")
Why use this method?
- It allows you to handle more complex CSV structures with dynamic column names.
- Using
DictReader
, you can reference columns by name rather than index, making the code easier to maintain. - It still processes the CSV file line by line, aligning with the approach of python read csv line by line.