能够在输入中使用任何情况在输出中生成相同的dict值

时间:2012-05-08 14:41:15

标签: python dictionary case

我有以下代码:

people = {'Bob' : {'phone' : '12',
            'birthday' : 'May',
            'address' : 'ABC',
            'interests' : ['a', 'b', 'c']},
        'Mary' : {'phone' : '13',
            'birthday' : 'April',
            'address' : 'CBA',
            'interests' : ['d', 'e', 'f']},

            response = ['']
wrong = "I don't know. Try again or type 'quit' to get out: " 
while response[0] != 'quit': 
    response = raw_input("Please enter who you're looking for, or type 'quit' to get out: ").split() 
    try:
        print "%s's %s is %s" % (response[0], response[1], people[response[0]][response[1]])  
    except KeyError: 
        print wrong,

我想这样做,所以输入可以在任何情况下仍然生成正确的输出。 例如。

'Mary phone', 'mary Phone', 'MARY PHONE'

全部给予

Mary's phone number is 13.

2 个答案:

答案 0 :(得分:3)

您应该使用capitalize()lower()

while response[0] != 'quit': 
    response = raw_input("Please enter who you're looking for, or type 'exit' to quit the program: ").split() 
    try:
        print "%s's %s is %s" % (response[0].capitalize(), response[1].lower(), people[response[0].capitalize()][response[1].lower()])  
    except KeyError: 
        print wrong,

如果你走这条路,你应该将'bob'密钥更改为'Bob' ...

或者,如果您重复使用结果,则可以节省更多的CPU周期,如下面的rubik所述。

while response[0] != 'quit': 
    response = raw_input("Please enter who you're looking for, or type 'exit' to quit the program: ").split() 
    try:
        fn, thing = response[0].capitalize(), response[1].lower()
        print "%s's %s is %s" % (fn, thing, people[fn][thing])  
    except KeyError: 
        print wrong,

答案 1 :(得分:2)

尝试通过str.lower()将输入转换为小写,确保输入始终为小写。然后确保所有people{}名称都是小写的,以便于搜索,并在输出时将输出格式化为大写名称。