简体   繁体   English

如何从python中的多个键中获取值

[英]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.对于上面的字典,如果我尝试通过说d["AGC"]来访问值 "S",编译器会给我一个关键错误。 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'

If you need to be able to retrieve items by their 3-digit code you can do so as follows.如果您需要能够通过他们的 3 位代码检索项目,您可以按如下方式进行。

 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

("UCU","UCC","UCA","UCG","AGU","AGC"):"S" doesn't mean "6 keys each with S as the value". ("UCU","UCC","UCA","UCG","AGU","AGC"):"S"并不意味着 "6 个键,每个键以 S 作为值"。 It means "one key of that whole tuple with S as the value".它的意思是“以 S 为值的整个元组的一个键”。 Unsurprisingly, when you then try to look it up with AGC , it doesn't find it.不出所料,当您尝试使用AGC查找它时,它没有找到。 You need to actually create separate keys.您需要实际创建单独的密钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM