使用元组作为字典键时,Python3给我KeyError

时间:2018-06-21 22:59:41

标签: python-3.x list dictionary for-loop

问题在于,很难在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',)

1 个答案:

答案 0 :(得分:1)

您的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)

让我知道您是否需要更好的说明。 附注-上面的代码假定您已定义morse字典。另外,我没有看到在此使用正则表达式的目的。