Give a dict (generate_translation_dict
) with triplets as keys and amino acids as values, I'd like to compare a list of triplets to the existing keys in that dictionary. If they equal each other, it should print the value.
For example:
generate_translation_dict = {'ATA': 'I',
'ATC': 'I',
'ATT': 'I',
'ATG': 'M',
}
comparison_list = [
'ATG',
'TTT',
'GTT',
]
If one of the items in list, for example 'ATG', is the same as a key from the dict, then it should print 'M'. The comparison list is imported from a text file and contains ~1200 items.
My code so far:
triplets = [] #This block imports the tripplets
with open('triplets.txt', 'r') as infile:
for line in infile:
line = line.strip('\n') # um \n zu entfernen
triplets.append(line)
aa = [] # aa for amino acids
with open('amino_acids.txt', 'r') as infile:
for line in infile:
line = line.strip('\n') # um \n zu entfernen
aa.append(line)
generate_translation_dict = {} # empty dictionary
for n in range(len(triplets)):
generate_translation_dict[triplets[n]] = aa[n] # adding elements to the dict # triplets added as keys/ aa added as value
print(generate_translation_dict)
tripletsequence = []
with open('triplet_sequence.txt', 'r') as infile:
for line in infile:
line = line.strip('\n') # um \n zu entfernen
tripletsequence.append(line)
As you can see, the tripletsequence is the list. The comparison should be a loop until the list is finished.
CodePudding user response:
Once you have the translation dict, all you need to do is iterate through triplet_sequence
and use the triplets as keys in the dict.
You can also greatly simplify the creation of the translation dict by zip
ping the two file streams and putting the result in a dict comprehension:
with open('triplets.txt') as triplets, open('amino_acids.txt') as aa:
translation = {
t.strip(): a.strip()
for t, a in zip(triplets, aa)
}
with open('triplet_sequence.txt') as f:
triplet_sequence = [
translation[t.strip()]
for t in f
]
print("\n".join(triplet_sequence))
% cat triplets.txt
ATA
ATC
ATT
ATG
% cat amino_acids.txt
I
I
I
M
% cat triplet_sequence.txt
ATG
ATT
ATC
% python test.py
M
I
I
CodePudding user response:
You can iterate over comparison_list
, check if an element in it is a key in generate_translation_dict
and if so, print the value at that key:
for x in comparison_list:
if x in generate_translation_dict:
print(generate_translation_dict[x])
In your example this prints M
.