1

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')

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

1 Answer 1

5

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.

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}
Sign up to request clarification or add additional context in comments.

3 Comments

@JonClements: Note to self: {k: v for k, v in iterable} == dict(iterable).. Thanks.
@JonClements: Want to write an answer too? :-P
sure - but I don't think "See Martijn's answer" is a valid answer ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.