python-3.x - 使用元组作为字典键时,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',)
解决方案
主要是你的 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
字典。此外,我没有看到在此使用正则表达式的目的。
推荐阅读
- django - 创建新测试用例时如何更改 kiwi 模板文本?
- javascript - java脚本中的这个范围
- string - Powershell convertfrom-string 自动将十进制解析为日期。我该如何防止这种情况?
- json - 在 groovy 中修改 REST 响应
- git - 通过使用 filter-repo 拆分现有仓库来创建新的 git 仓库
- java - 如何从实体管理器查询中获取总结果计数
- sql - 用于查找 count < 2 的记录的 SQL 查询
- openssl - 使用 Openssl s_server 限制密码套件选择
- android - 如何在android的状态栏上方显示吐司?
- nutch - 处理网页抓取的文本时不要删除多余的行