简体   繁体   English

来自CSV文件python的字典

[英]dictionary from csv file python

I have read a cvs file and I would like to create a dictionary from the information I have on that file. 我已经阅读了cvs文件,并且想根据该文件上的信息来创建字典。 I´ve tried to use class csv.DictReader to that propose but it didnt gave me the results i wanted. 我曾尝试使用csv.DictReader类提出该建议,但并没有给我想要的结果。

Now i am reading the file like this: 现在我正在读取这样的文件:

size_reader = csv.reader(f,dialect='excel-tab')

and I have as result this: 结果是:

['chr1', '249250621']
['chr2', '243199373']
['chr3', '198022430']
['chr4', '191154276']
['chr5', '180915260']

I would like to make a dictionary with this structure: 我想用这种结构制作字典:

dict ['chr4'] = 191154276
dict ['chr5'] = 180915260
dict ['chr2'] = 243199373

I tried regular expressions to split the elements the lines on the file but I had no success with it, maybe i used the wrong characters in the split function. 我尝试使用正则表达式将元素的行拆分为文件上的行,但是我没有成功,也许是在split函数中使用了错误的字符。 Could you give some suggestion of how to separate the elements and built the dictionary? 您能否提出一些有关如何分离元素和构建词典的建议?

Just convert it to a dict directly: 只需将其直接转换为字典即可:

 result = dict(size_reader)

This takes each two-column result from your size_reader CVS reader and uses that as the key and value for a python dictionary. 这将从您的size_reader CVS阅读器的每个两列结果中获取,并将其用作python字典的键和值。

To convert each value to integers, you'd need to use a dict comprehension to process each value: 要将每个值转换为整数,您需要使用dict理解来处理每个值:

result = {k: int(v) for k, v in size_reader}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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