gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:53:44 24 4
gpt4 key购买 nike

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"}

对于上面的字典,如果我尝试通过说 d["AGC"] 来访问值“S”,编译器会给出一个关键错误。我尝试查看此处的其他问题,但找不到答案。

错误:

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.

 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]

使用

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

关于python - 如何从Python中的多个键获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59550109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com