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:
Month | Average | 2005 | 2006 |
---|---|---|---|
May | 0.1 | 0 | 0 |
Jun | 0.5 | 2 | 1 |
Jul | 0.7 | 5 | 1 |
Aug | 2.3 | 6 | 3 |
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', '': ''}