gaurav shinde
gaurav shinde

Reputation: 31

How to get value from multiple keys in python

d = {"AUG":"M",
("UAA","UAG","UGA"):'',
("GCU","GCC","GCA","GCG"):"A",
("CGU","CGC","CGA","CGG","AGA","AGG"):"R",
("AAU","AAC"):"N",
("GAU","GAC"):"D",
("UGU","UGC"):"C",
("UCU","UCC","UCA","UCG","AGU","AGC"):"S",
("CCU","CCC","CCA","CCG"):"P",
("ACU","ACC","ACA","ACG"):"T",
("GUU","GUC","GUA","GUG"):"V",
("UUA","UUG","CUU","CUC","CUA","CUG"):"L",
("AUU","AUC","AUA"):"I",
("UUU","UUC"):"F",
("UAU","UAC"):"Y",
("CAU","CAC"):"H",
("CAA","CAG"):"Q",
("AAA","AAG"):"K",
("GAA","GAG"):"E",
"UGG":"W",
("GGU","GGC","GGA","GGG"):"G"}

For the above dict, if I try to access the value "S" by saying d["AGC"], compiler gives me a key error. I tried to look at other questions on here but I couldn't find answer.

Error:

Traceback (most recent call last):   File "p_synt.py", line 94, in <module>
    print(d[str[:3]]) KeyError: 'AGC'

Upvotes: 1

Views: 377

Answers (2)

DarrylG
DarrylG

Reputation: 17176

If you need to be able to retrieve items by their 3-digit code you can do so as follows.

 def find_value(d, key):
    # check if complete key
    if key in d:
        return d[key]

    # check if in a key list
    for k, v in d.items():
        if isinstance(k, tuple) and key in k:
            return d[k]

Usage

print(find_value(d, "AGC"))  
>>> S
print(find_value(d, "UGG"))
>>> W

Upvotes: 2

("UCU","UCC","UCA","UCG","AGU","AGC"):"S" doesn't mean "6 keys each with S as the value". It means "one key of that whole tuple with S as the value". Unsurprisingly, when you then try to look it up with AGC, it doesn't find it. You need to actually create separate keys.

Upvotes: 1

Related Questions