如何在python中打印用户输入的值的键

时间:2017-12-01 04:00:12

标签: python python-3.x

我正在使用python 3.6,我必须将密钥打印到用户输入的值。我给出了一长串的省份和与邮政编码相关的首字母,这样当用户输入一个6字母的邮政编码时,该程序将打印该邮政编码所在的省份。 *我不允许使用if语句,循环或列表。* 这就是我到目前为止所做的:

    data = {}

    # Initialize dictionary so that it maps from Province to correlated first letter         
    data = {"Alberta": "T",
            "British Columbia":"V",
            "Manitoba":"R",
            "New Brunswick": "E",
            "Newfoundland":"A",
            "Nova Scotia": "B",
            "Nunavut": "X",
            "Northwest Territories": "X",
            "Ontario": ["K,L,M,N,P"],
            "Prince Edward Island": "C",
            "Quebec":"[G,H,J]",
            "Saskatchewan":"S",
            "Yukon":"Y"}


    # Read a postal code from the user

    key = input("Enter a 6 character postal code (A1A1A1): ")

    #computer letters to uppercase
    key = key.upper()
    print("That postal code resides in", (data[key]))

然而,它给出了print(data [key])语句的错误消息。我也在努力找出一种方法,以便我可以输入输入的6个值并打印省,没有错误,因为我的省与一个值相关。我刚刚学习了词典,我遇到了解决这个问题的麻烦。任何帮助都会很棒!!非常感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用filter

key = input("Enter a 6 character postal code (A1A1A1): ")
data = {"Alberta": "T",
        "British Columbia":"V",
        "Manitoba":"R",
        "New Brunswick": "E",
        "Newfoundland":"A",
        "Nova Scotia": "B",
        "Nunavut": "X",
        "Northwest Territories": "X",
        "Ontario": ["K,L,M,N,P"],
        "Prince Edward Island": "C",
        "Quebec":"[G,H,J]",
        "Saskatchewan":"S",
        "Yukon":"Y"}
options = list(filter(lambda x:x[-1].startswith(key.upper()) if not isinstance(x[-1], list) else x[-1][0] == key , data.items()))
options = "Code not found" if not options else list(options)[0][0]

key = 'A'时的输出:

'Newfoundland'

答案 1 :(得分:1)

字典以<key>:<value>顺序声明,因此您最好将字典切换为“T”:“Alberta”然后您可以在没有if语句和循环的情况下完成任务 data = {"T": "Alberta", "V":"British Columbia", "R":"Manitoba", "E":"New Brunswick", "A":"Newfoundland", "B":"Newfoundland", "X":["Nunavut","Northwest Territories"], "K":"Ontario", "L":"Ontario", "M":"Ontario", "N":"Ontario", "P":"Ontario", "N":"Ontario", "G":"Quebec", "H":"Quebec", "J":"Quebec", "S":"Saskatchewan", "Y":"Yukon"}