python - 编写一个小型 Python 字典
问题描述
我试图写一个小字典,其中第一行有一个 n 数字,表示字典中的单词数。接下来的 n 行中的每一行都由两个单词组成,表示第二个单词表示第一个单词。下一行包含一个句子。一个句子由几个用空格分隔的单词组成。
当用户输入 Hello 词时,我试图将输出中的单词 salam 可视化给用户。
我可以写的代码是这样的:
dic = {
'Hello': 'Salam',
'Goodbye': 'Khodafez',
'Say': 'Goftan',
'We': 'Ma',
'You': 'Shoma'
}
n = int(input())
usrinp = input()
for i in range(n):
for i in dic:
if usrinp in dic:
print(i + ' ' + dic[i])
else:
usrinp = input()
解决方案
读取用户输入。重复多次 - 使用get
处理KeyError
自身的属性从字典中获取项目:
dic = {'Hello': 'Salam', 'Goodbye': 'Khodafez', 'Say': 'Goftan', 'We': 'Ma', 'You': 'Shoma'}
n = int(input())
for _ in range(n):
print(dic.get(input(), 'Wrong Input'))
编辑:
dic = {'Hello': 'Salam', 'Goodbye': 'Khodafez', 'Say': 'Goftan', 'We': 'Ma', 'You': 'Shoma'}
n = int(input())
for _ in range(n):
usrinp = input()
print(dic.get(usrinp, usrinp))
推荐阅读
- amazon-web-services - 使用书签使用 AWS Glue 处理未分区的数据
- cordova - 使用 ionic 3 和 cordova 8 提醒另一个应用程序
- javascript - insertImage 到工作表中的 blob 大小是否有限制(Google App Script)?
- laravel - 如何将表数据从控制器输出到视图?
- google-cloud-platform - BigQuery 如何读取 Google Cloud Storage 中 Parquet 文件的架构?
- python - 奇怪的函数行为(浮点问题)
- python - 如何在使用 matplotlib 绘图时在 x 轴上绘制均匀间隔的值
- c# - 是否可以使用 ASP.NET 从相应的 .cs 文件中定位 .aspx 文件中的 html 元素?
- javascript - 我在 Windows 终端上执行 JavaScript 文件时遇到问题
- php - 如何在 MySQL 查询中包含 PHP 变量