如果关键字已在字典中,则返回值

2024-05-03 10:31:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在为compsci课程做最后的作业。 其基本思想是创建一个简单的加密程序。 它使用一个文件输入,其中包含一行映射到不同字母(即z到a、y到b、w到c等)的字母表,并创建两个字典(编码和解码)供以后使用,并返回0。 该函数还需要测试可能出现的不同问题,并返回不同的值。我一直坚持的是,如果键或值已经添加到字典中,则分别返回3或4

encoding = {}
decoding = {}
def createDictionaries(filepath):
    global encoding
    global decoding
    try:
        with open(filepath) as f:
            for line in f:
                try:
                    (key, val) = line.split()
                except ValueError:
                    return 2
                encoding[(key)] = val
                decoding[(val)] = key
            return 0

    except FileNotFoundError:
        return 1


print(createDictionaries("dict1.txt"))

我尝试过使用for循环和异常捕获,但似乎无法破解它

非常感谢您的帮助


Tags: keyforreturn字典linevalglobalencoding
2条回答

可以在将键和值添加到字典之前添加if语句:

encoding = {}
decoding = {}
def createDictionaries(filepath):
    global encoding, decoding

    try:
        with open(filepath,'r') as f:
            for line in f.readlines():
                try:
                    (key, val) = line.split()
                except ValueError:
                    return 2
                if key in encoding.keys(): # If this condition is met, return 3
                    return 3
                if val in encoding.values(): # If this condition is met, return 4
                    return 4
                encoding[key] = val
                decoding[val] = key
            return 0

    except FileNotFoundError:
        return 1

print(createDictionaries("dict1.txt"))

要检查字典中是否有键或值,可以使用if key in dic.keys():if value in dic.values():

相关问题 更多 >