Python中的字典 - 检查密钥

时间:2015-12-17 03:11:02

标签: python

这是我到目前为止编写的代码:

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之间的数字,然后打印其序号。我无法使用输入并检查它是否是一个键,然后将其值作为主函数中的print语句返回。该错误与if语句有关。

4 个答案:

答案 0 :(得分:3)

试试这个......

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()

不需要if检查,因为dict.get可以返回默认值。

答案 1 :(得分:1)

您的问题出在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), "")是一种更清洁的方式。

答案 2 :(得分:0)

要添加到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()

请注意,我通过输入行添加了eval。

答案 3 :(得分:0)

也许是这样的?如果输入无效密钥,请勿打印输出。

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