3

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)])
GuyOverThere
  • 89
  • 2
  • 8

2 Answers2

5

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])
Selcuk
  • 57,004
  • 12
  • 102
  • 110
0

Here's a pandas solution:

import pandas as pd
df =  pd.DataFrame(list(xdict.items()))

def lookupKey(df, key):
  return df[df[1].apply(lambda x: True if key in x else x) == True][0].reset_index()[0][0]

lookupKey(df, 'CGU')
# 'Arginine'
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24