Python 使用元组和字典的字谜查找器

Python 使用元组和字典的字谜查找器,python,dictionary,tuples,Python,Dictionary,Tuples,因此,我有一个程序,它接受一个字符串,并返回一个元组,其中字符串中的所有字母按排序顺序排列 然后,程序需要创建一个字典,元组作为键,值是包含键的所有单词的列表 到目前为止,我已经: _DEBUG = True def getLetters(string): """Purpose, to nab letters from a string and to put them in a tuple in sorted order.""" #sort the letters and

因此,我有一个程序,它接受一个字符串,并返回一个元组,其中字符串中的所有字母按排序顺序排列

然后,程序需要创建一个字典,元组作为键,值是包含键的所有单词的列表

到目前为止,我已经:

_DEBUG = True
def getLetters(string):
    """Purpose, to nab letters from a string and to put them in a tuple in
    sorted order."""
    #sort the letters and put them in a tuple
    tuple_o_letters = tuple(sorted(string))
    if _DEBUG:

    print tuple_o_letters
    return tuple_o_letters
def main():
    try:# open the file
        fin = open("words2.txt")
    except:
        #if file doesn't exist
        print("no, no, file no here.")
        sys.exit(0)
    wordList = [] #create a word list
    for eachline in fin:
        #fill up the word list and get rid of new lines
        wordList.append(eachline.strip())

    word_dict = {} # create a dictionary
    for eachWord in wordList:
        tuple = getLetters(eachWord) # make a tuple out of each word
        word_dict[tuple] = wordList #store it into a dictionary

    print word_dict #print out the dictionary


if __name__ == '__main__':
    main()
现在,虽然我可以将元组存储为字典键,但我不知道的是,当且仅当单词列表具有这些键时,如何将单词列表存储为值

例如: 如果在字典中有键,('d','o','g'),我会得到该特定条目的值god和dog,假设这两个单词在单词列表中(从words2.txt文件中获取)。

您存储的是整个单词列表。您只想存储每个已排序字母元组的匹配单词:

word_dict = {} # create a dictionary

for eachWord in wordList:
    key = getLetters(eachWord) # make a tuple out of each word
    if key in word_dict:
        word_dict[key].append(eachWord)
    else:
        word_dict[key] = [eachWord]
如果给定的键(字母元组)还不存在,则会为该键创建一个列表,否则只会追加单词

您可以使用以下方法简化此过程:


因为这样您就不需要每次都显式地测试密钥。

我编写了这段代码,但它似乎将执行放入了一个无限循环。@user1768884:然后您需要重新检查代码;我的示例无法创建无限循环。
from collections import defaultdict

word_dict = defaultdict(list)

for eachWord in wordList:
    word_dict[getLetters(eachWord)].append(eachWord)