首页 > 解决方案 > 如何从用户那里获取输入以在字典中查找键并输出其值?

问题描述

我在 python 中制作了一个简单的 S-Box,它包含所有可能的 3 位组合作为键,其加密组合作为它的值。

它基本上会从用户那里获取 3 位,然后针对我定义的 S-Box 表运行它,然后它会找到与用户输入位匹配的密钥并输出其加密值

下面的示例代码,不是完整的代码;

SBox= { "000": "110","001": "010","010":"000","011": "100" }

inputBits= input("Enter 3 bit pattern: ")

if inputBits == "000":
        print("Encrypted combo: ", SBox["000"])

输出:

Enter 3 bit pattern: 000
Encrypted combo: 110

我希望能够更有效地做到这一点,即:不必为每个可能的组合都有一个 if,类似于将输入字符串与字典中的键匹配的东西。

任何帮助表示赞赏!

标签: pythonpython-3.xdictionary

解决方案


利用dict.get

前任:

SBox= { "000": "110","001": "010","010":"000","011": "100" }

inputBits= input("Enter 3 bit pattern: ")

if SBox.get(inputBits):
    print("Encrypted combo: ", SBox.get(inputBits))

#OR print("Encrypted combo: ", SBox.get(inputBits, "N\A"))

推荐阅读