簡體   English   中英

Python中的字典-檢查密鑰

[英]Dictionary in Python - checking for key

這是我到目前為止編寫的代碼:

def Ordinal(check):
    data={1:"First", 2:"Second", 3:"Third", 4:"Fourth", 5:"Fifth", 6:"Sixth", 7:"Seventh", 8:"Eighth", 9:"Ninth", 10:"Tenth", 11:"Eleventh", 12:"Twelfth"}

    if check in dict.keys: 
        return dict.get(check)
    else:
        return""
def main():
    Num=input("Enter a number (1-12) to get its ordinal: ")
    print ("The ordinal is", Ordinal(Num))
main()          

該程序假設從用戶那里獲得1到12之間的數字,然后打印其序數。 我在使用輸入時遇到麻煩,並檢查它是否為鍵,然后在主函數中將其值作為打印語句返回。 該錯誤與if語句有關。

嘗試這個 ...

def Ordinal(check):
    data={1:"First", 2:"Second", 3:"Third", 4:"Fourth", 5:"Fifth", 6:"Sixth", 7:"Seventh", 8:"Eighth", 9:"Ninth", 10:"Tenth", 11:"Eleventh", 12:"Twelfth"}
    return data.get(int(check), "")

def main():
    Num=input("Enter a number (1-12) to get its ordinal: ")
    print ("The ordinal is", Ordinal(Num))
main()

由於dict.get可以返回默認值,因此不需要if檢查。

您的問題在於if check in data.keys:因為:

data.keys是一種方法: <built-in method keys of dict object at 0x10b989280>

您應該調用方法data.keys()返回[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

或者,您可以執行以下操作:

def Ordinal(check):
    data={1:"First", 2:"Second", 3:"Third", 4:"Fourth", 5:"Fifth", 6:"Sixth", 7:"Seventh", 8:"Eighth", 9:"Ninth", 10:"Tenth", 11:"Eleventh", 12:"Twelfth"}

    if check in data:
        return data.get(check)
    else:
        return""
def main():
    Num=input("Enter a number (1-12) to get its ordinal: ")
    print ("The ordinal is", Ordinal(Num))
main()

或就像@astrosyam指出的那樣,使用data.get(int(check), "")是一種更干凈的方法。

要增加Bryan Oakley的答案,您可以執行以下操作:

def Ordinal(check):
    data={1:"First", 2:"Second", 3:"Third", 4:"Fourth", 5:"Fifth", 6:"Sixth", 7:"Seventh", 8:"Eighth", 9:"Ninth", 10:"Tenth", 11:"Eleventh", 12:"Twelfth"}

    if check in data:
        return data.get(check)
    else:
        return""
def main():
    Num=eval(input("Enter a number (1-12) to get its ordinal: ")) #notice eval here!
    print ("The ordinal is", Ordinal(Num))
main()

注意,我在輸入行中添加了評估。

也許是這樣的嗎? 如果他們輸入了無效的密鑰,請不要打印輸出。

data = {
    1: "First", 2: "Second", 3: "Third", 4: "Fourth", 5: "Fifth",
    6: "Sixth", 7: "Seventh", 8: "Eighth", 9: "Ninth", 10: "Tenth",
    11: "Eleventh", 12: "Twelfth"}


def Ordinal(check):
    return data[check]


def main():
    Num = input("Enter a number (1-12) to get its ordinal: ")

    try:
        print ("The ordinal is {}".format(Ordinal(int(Num))))
    except ValueError:
        print("didnt enter a valid integer")
    except KeyError:
        print("Not number between 1-12")

main()

如果使用python 2.x,請使用raw_input而不是input

暫無
暫無

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

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