首页 > 解决方案 > 编写一个小型 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()

标签: pythonpython-3.x

解决方案


读取用户输入。重复多次 - 使用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))

推荐阅读