从csv文件中提取数据并用python编写字典

2024-09-27 23:26:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个csv文件:

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

我怎样才能把这些数据编成这样的字典:

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

Tags: 文件csv数据data字典dictcountrycodedubaiareacode
1条回答
网友
1楼 · 发布于 2024-09-27 23:26:32

Python有一个csv模块,文档是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:]

相关问题 更多 >

    热门问题