Convert CSV Into Dictionary in Python

To convert a CSV file to a Python dictionary use the DictReader() method from the csv package. Dictionaries are a key-value data type meaning the header (first row) of the CSV will be the keys and the rest of the values will be paired with the correct key.

 

Here is a table representation of a CSV that we will open and parse as a dictionary:

 

MonthAverage20052006
May0.100
Jun0.521
Jul0.751
Aug2.363

 

import csv

with open('sample1.csv', 'r') as file:
   reader = csv.DictReader(file, skipinitialspace=True)
   
   for l in reader:
       print(l)
{'Month': 'May', 'Average': '0.1', '2005': '0', '2006': '0', '': ''}
{'Month': 'Jun', 'Average': '0.5', '2005': '2', '2006': '1', '': ''}
{'Month': 'Jul', 'Average': '0.7', '2005': '5', '2006': '1', '': ''}
{'Month': 'Aug', 'Average': '2.3', '2005': '6', '2006': '3', '': ''}