简体   繁体   中英

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']}

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:]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM