字典从csv文件python [英] dictionary from csv file python

查看:136
本文介绍了字典从csv文件python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读过一个cvs文件,我想从该文件中的信息中创建一个字典。我试图使用类csv.DictReader的建议,但没有给我我想要的结果。

I have read a cvs file and I would like to create a dictionary from the information I have on that file. I´ve tried to use class csv.DictReader to that propose but it didnt gave me the results i wanted.

现在我正在读这个文件:

Now i am reading the file like this:

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

我的结果是:

['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. Could you give some suggestion of how to separate the elements and built the dictionary?

推荐答案

直接将其转换为dict: / p>

Just convert it to a dict directly:

 result = dict(size_reader)

这需要您的 size_reader CVS阅读器的每个两列结果,并将其用作python字典的键和值。

This takes each two-column result from your size_reader CVS reader and uses that as the key and value for a python dictionary.

要将每个值转换为整数,您需要使用字母理解来处理每个值:

To convert each value to integers, you'd need to use a dict comprehension to process each value:

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

这篇关于字典从csv文件python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆