//Python code to read csv into dictionary

Python code to read csv into dictionary

This code is an example of how to read a csv file into a dictionary data structure. This code reads two values from the input csv, an ID and a date. The date is stored as a datetime object in the dictionary. The code is made more generalisable by using three parameters related to the input csv file. A parameters is used to identify each of the column numbers for the id and date, and also the the format of the date.

def readFileAsDictionary(fileName,columnID,columnDate,inputDateFormat='%d/%m/%Y'):

with open(fileName, 'rb') as f:
reader = csv.reader(f)
next(reader)#skip header
inputFileList = list(reader)

for item in inputFileList:
datetime_object = datetime.datetime.strptime(item[columnDate],inputDateFormat)

return returnDictionary