簡體   English   中英

如果鍵已經在字典中,則返回值

[英]return value if key already in dictionary

我目前正在為 Compsci 課程做最后的作業。 基本思想是創建一個簡單的加密程序。 它使用包含映射到不同字母的字母表行的文件輸入(即 z 到 a、y 到 b、w 到 c 等)並創建兩個字典(編碼和解碼)以供稍后使用並返回 0。 function還需要測試可能出現的不同問題並返回不同的值。 我堅持的部分是如果鍵或值已經添加到字典中,分別返回 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 循環和異常捕獲,但似乎無法破解它

非常感謝任何幫助。

要檢查一個鍵或一個值是否在字典中,您可以使用if key in dic.keys(): if value in dic.values():

您可以在將鍵和值添加到字典之前添加 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"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM