Creating a dictionary from a text archive (Codon table)

Question:

I want to create a dictionary with an archive that I’ve downloaded from Rosalind Code Project. I saved it like table.txt and written this code:

d = {}
with open('./table.txt',"r") as f:
a = f.read().split()
for line in a:
    if len(line) == 3: k = line; d[line] == '';
    elif len(line) == 1 | len(line) == 4: d[k] = line;

But, I get this error:

Traceback (most recent call last):
File “”, line 5, in
KeyError: ‘UUU’

This ‘UUU’ is referred to as the first word in the table.txt file. I’m trying to save every word in a inside a d dictionary. If the first element starts with a codon is saved as a key. Everything else is saved as an amino acid value with the last key created.

Thanks for any help you will provide to me.

Asked By: Adonis Cedeño

||

Answers:

maybe you want this

d = {}
with open('./table.txt',"r") as f:
    a = f.read().split()
for line in a:
    if len(line) == 3:
        k = line
    elif len(line) == 1 or len(line) == 4:
        d[k] = line

if table.txt is well formatted. this is possible

for pre, next in zip(a[:-1:2], a[1::2]):
    d[pre] = next
Answered By: bokgae