Python字典,键和字符串

时间:2015-05-01 15:13:00

标签: python function dictionary key

我试图编写一个带变量的程序,其中包含一个字典,其中键是一个单词字符串,值是字符串列表。每个字符串都是单词/键的定义。

我想要做的是询问用户一个字;如果它不在词典中。然后我显示一条错误信息,如果是,则打印出每个定义,从1开始编号。

我无法理解如何在不同的行上调用不同的定义并对它们进行编号。这就是我到目前为止所做的:

def Dict(webdict):
    word_user = raw_input('Word ==> ')
    i =0
    if word_user in webdict:
        while i <= len(webdict['word_user']):
            print str(i+1) + '.', webdict['word_user'][i]
            i+=1
    else:
        print '"' + word_user + '"', 'not found in webdict.'

Dict(webdict)

一些示例输出:

Word ==> python
1. a large heavy-bodied nonvenomous constrictor snake occurring throughout the Old World tropics
2. a high-level general-purpose programming language

Word ==> constrictor
Word “constrictor” not found in webster

谢谢!

1 个答案:

答案 0 :(得分:2)

  1. 当您对webdict编制索引时,密钥应为word_user,而不是'word_user'。后者是字符串文字,而不是用户输入的内容。

  2. 您的while循环超过列表末尾。将<=更改为<,或只使用forenumerate

  3. def Dict(webdict):
        word_user = raw_input('Word ==> ')
        i =0
        if word_user in webdict:
            while i < len(webdict[word_user]):
                print str(i+1) + '.', webdict[word_user][i]
                i+=1
        else:
            print '"' + word_user + '"', 'not found in webdict.'
    
    webdict = {"Python": ["A cool snake", "A cool language"]}
    Dict(webdict)
    

    或者

    def Dict(webdict):
        word_user = raw_input('Word ==> ')
        if word_user in webdict:
            for i, definition in enumerate(webdict[word_user], 1):
                print str(i+1) + '.', definition
        else:
            print '"' + word_user + '"', 'not found in webdict.'
    
    webdict = {"Python": ["A cool snake", "A cool language"]}
    Dict(webdict)
    

    结果:

    Word ==> Python
    1. A cool snake
    2. A cool language