Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the key of a dictionary, searching for a value in the list of values

I know this is a duplicate. However, the answer to that particular question does not work for me. Link to the question here.

How do you print the key of a dictionary from the dictionary's value?

My code:

xdict = {
  "Phenylalanine": ["UUU", "UUC"], "Leucine": ["UUA", "CUU", "CUC", "CUA", "CUG", "UUG"],
  "Isoleucine": ["AUU", "AUC", "AUA"], "Methionine": "AUG", "Valine": ["GUU", "GUC", "GUA", "GUG"],
  "Serine": ["UCU", "UCC", "UCA", "UCG"], "Proline": ["CCU", "CCC", "CCA", "CCG"],
  "Threonine": ["ACU", "ACC", "ACA", "ACG"], "Alanine": ["GCU", "GCC", "GCA", "GCG"],
  "Tyrosine": ["UAU", "UAC"], "Histidine": ["CAU", "CAC"], "Glutamine": ["CAA", "CAG"],
  "Asparagine": ["AAU", "AAC"], "Lysine": ["AAA", "AAG"], "Asparatic Acid": ["GAU", "GAC"],
  "Glutamic Acid": ["GAA", "GAG"], "Cysteine": ["UGU", "UGC"], "Trytophan": "UGG",
  "Arginine": ["CGU", "CGC", "CGA", "CGG", "AGG", "AGA"], "Serine": ["AGU", "AGC"],
  "Glycine": ["GGU", "GGC", "GGA", "GGG"]
}

a = input("Enter your DNA sequence: ")
print(list(xdict.keys())[list(xdict.values()).index(a)])
like image 790
GuyOverThere Avatar asked Nov 24 '25 23:11

GuyOverThere


1 Answers

It is easier to create a reversed lookup dictionary:

>>> lookup_dict = {k: key for key, values in xdict.items() for k in values}
>>> lookup_dict["UUC"]
'Phenylalanine'

You can apply this to your code as follows:

lookup_dict = {k: key for key, values in xdict.items() for k in values}
a = input("Enter your DNA sequence: ")
print(lookup_dict[a])
like image 179
Selcuk Avatar answered Nov 27 '25 12:11

Selcuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!