Sudipta Swarnakar Sudipta Swarnakar - 15 days ago 6
Python Question

Convert csv file into python dictionary

I want to convert

A,B,24
type CSV file into a dictionary having format like
{'A':{'B':24}}
.

Answer

For an input.csv CSV file holding:

A,B,24

This could be done as follows:

import csv

my_dict = {}

with open('input.csv') as f_input:
    for row in csv.reader(f_input):
        my_dict[row[0]] = {row[1] : row[2]}

print my_dict

Giving you:

{'A': {'B': '24'}}