I want to write a function where any keys can be extracted to give the values. Here is the dictionary and the code that I wrote and the input:
DNAcodon2aa = {"aaa":"K", "aac":"N", "aag":"K", "aat":"N",
"aca":"T", "acc":"T", "acg":"T", "act":"T",
"aga":"R", "agc":"S", "agg":"R", "agt":"S",
"ata":"I", "atc":"I", "atg":"M", "att":"I",
"caa":"Q", "cac":"H", "cag":"Q", "cat":"H",
"cca":"P", "ccc":"P", "ccg":"P", "cct":"P",
"cga":"R", "cgc":"R", "cgg":"R", "cgt":"R",
"cta":"L", "ctc":"L", "ctg":"L", "ctt":"L",
"gaa":"E", "gac":"D", "gag":"E", "gat":"D",
"gca":"A", "gcc":"A", "gcg":"A", "gct":"A",
"gga":"G", "ggc":"G", "ggg":"G", "ggt":"G",
"gta":"V", "gtc":"V", "gtg":"V", "gtt":"V",
"taa":"*", "tac":"Y", "tag":"*", "tat":"T",
"tca":"S", "tcc":"S", "tcg":"S", "tct":"S",
"tga":"*", "tgc":"C", "tgg":"W", "tgt":"C",
def translate(codon_list):
"""This function translates a list of codons into a primary amino acid sequence. """
codon_list = DNAcodon2aa.keys()
newcodon = ''.join(codon_list)
protein = ''
for i in range(0, len(newcodon),3):
codon = newcodon[i:i 3]
protein = DNAcodon2aa[codon]
return protein
input
translate(['tct','act','gct','gcc'])
output wanted:
'STAA'
output produced
'KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*TSSSS*CWCLFLF'
it gave me the concatenation of all values in the dict instead of the values of certain keys in the input. I have tried and researched all possible codes that I could do but failed. any help would be appreciated.
CodePudding user response:
@quamrana's comment correctly diagnoses the problem with your code. You overwrite codon_list
with the keys from DNAcodon2aa
. That line should be deleted. It should work after that.
That said, here's a better implementation of your function:
def translate(codon_list):
return ''.join(DNAcodon2aa[codon] for codon in codon_list)
CodePudding user response:
You need to remove some code from your original function:
def translate(codon_list):
"""This function translates a list of codons into a primary amino acid sequence. """
protein = ''
for codon in codon_list:
protein = DNAcodon2aa[codon]
return protein
Results:
>>> print(translate(['tct', 'act', 'gct', 'gcc']))
STAA
CodePudding user response:
Use str.join
def translate(codon_list):
return ''.join(DNAcodon2aa.get(i) for i in codon_list)
If your input list has some unexpected values and you need to skip the value, you can use it like this.
codon_list = ['tct','act','gct','gcc', 'unexpected']
def translate(codon_list):
return ''.join(DNAcodon2aa.get(i, '') for i in codon_list)
print(translate)
# 'STAA'