Search code examples
pythondictionarydna-sequence

python: read dna sequence text file to dictionary


I'm trying to convert a text file containing DNA sequences to a dictionary in python. The file is setup in columns.

TTT F
TCT S
TAT Y
TGT C
TTC F


import os.path

if os.path.isfile("GeneticCode_2.txt"):
    f = open('GeneticCode_2.txt', 'r')
    my_dict = eval(f.read())

Trying to get it to:

my_dict = {TTT: F, TCT: S, TAT: Y} 

Solution

  • You can use the dict constructor using an iterable of pairs (2-tuples) and pass it the split lines of your file:

    with open('GeneticCode_2.txt', 'r') as f:
        my_dict = dict(line.split() for line in f)  
        # works only if file only contains lines that split into exactly 2 tokens