Wednesday, September 4, 2013

Python - Get dictionary data from csv file

Read the csv file, and put the data into a dictionary:


#!/usr/bin/python

import csv


def csv_to_dict(csv_file_path):

    csv_file = open(csv_file_path, 'rb')
    csv_file.seek(0)
    sniffdialect = csv.Sniffer().sniff(csv_file.read(10000), delimiters='\t,;')
    csv_file.seek(0)
    dict_reader = csv.DictReader(csv_file, dialect=sniffdialect)
    csv_file.seek(0)
    dict_data = []
    for record in dict_reader:
        dict_data.append(record)


    csv_file.close()


    return dict_data