首页 > 解决方案 > 使用元组作为字典键时,Python3 给了我 KeyError

问题描述

问题是在 for 循环中很难将输入用作字典的键,我尝试使用 tuple 和 list ,但结果相同

这是代码:

import re
morse = {
"A" : ".-", 
"B" : "-...", 
"C" : "-.-.", 
"D" : "-..", 
"E" : ".", 
"F" : "..-.", 
"G" : "--.", 
"H" : "....", 
"I" : "..", 
"J" : ".---", 
"K" : "-.-", 
"L" : ".-..", 
"M" : "--", 
"N" : "-.", 
"O" : "---", 
"P" : ".--.", 
"Q" : "--.-", 
"R" : ".-.", 
"S" : "...", 
"T" : "-", 
"U" : "..-", 
"V" : "...-", 
"W" : ".--", 
"X" : "-..-", 
"Y" : "-.--", 
"Z" : "--..", 
"0" : "-----", 
"1" : ".----", 
"2" : "..---", 
"3" : "...--", 
"4" : "....-", 
"5" : ".....", 
"6" : "-....", 
"7" : "--...", 
"8" : "---..", 
"9" : "----.", 
"." : ".-.-.-", 
"," : "--..--",
" " : " "
}
print("""
                        MORSECODE ENCYPTER """)
print("Enter the text to convert(keep in mind that upper case character, numbers , (.) and (,) are only allowed) :",end = '')
to_encrypt = input()
tuple1 =  tuple( re.findall("." , to_encrypt) )
print (tuple1)  
for i in tuple1 :
    print(morse[tuple1])    

当我输入 to_encrypt 输入(例如 H)时,它给了我:

Traceback (most recent call last):
File "x.py", line 50, in <module>
print(morse[tuple1])    
KeyError: ('H',)

标签: python-3.xlistdictionaryfor-loop

解决方案


主要是你的 for 循环似乎是不正确的,你可以试试这个:

to_encrypt = list(str(input()))

for ch in to_encrypt:
    morse_val = morse.get(ch, None)

    if not morse_val:
        print('could not encode ', ch)

    else:
        print(morse_val)

如果您需要更好的说明,请告诉我。PS - 上面的代码假设您已经定义了morse字典。此外,我没有看到在此使用正则表达式的目的。


推荐阅读