MHS
MHS

Reputation: 2350

Extracting the data from a csv file amd making dictionary of it using python

I have a csv file like this:

001,citycode,countrycode,usacode,usacountrycode
00457,citycode,countrycode,ugandacode,kampalacode
00976,countrycode,dubaicode,uaecode,dubaiareacode

How can I make a dictionary of this data like this:

data_dict = {'001' : ['citycode', 'countrycode', 'usacode', 'usacountrycode'],
             '00457' : ['citycode', 'countrycode', 'ugandacode', 'kampalacode'],
             '00976' : ['countrycode', 'dubaicode', 'uaecode', 'dubaiareacode']}

Upvotes: 0

Views: 115

Answers (1)

sean
sean

Reputation: 3985

Python has a csv module, the documentation is here.

>>> import csv
>>> your_dict = {}
>>> with open('eggs.csv', 'rb') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
...     for row in spamreader:
...         your_dict[row[0]] = row[1:]

Upvotes: 1

Related Questions