如何在字典中递归创建字典?

时间:2016-12-07 00:59:16

标签: python dictionary

我正在读一本字典文件,我想创建这样的东西:

Word     First    Second   Third    Fourth
Length   Letter   Letter   Letter   Letter   ...

3  -->   c   -->  a   -->  t
                      -->  r
                      -->  b
             -->  o   -->  p
                      -->  b
   -->   b   -->  e   -->  t
                      -->  g
4  -->   p   -->  u   -->  n   -->  t
...

希望你明白了。我希望能够像下面一样对着Dictionary测试一组数据。显然只是一个基本的例子,而不是它将如何完成。

smallDictionary = dictionary[3]
found = []
if dataArr[0][0] in smallDictionary:
    if dataArr[0][1] in smallDictionary:
        if dataArr[0][2] in smallDictionary:
            found.append(''.join([dataArr[0][0],dataArr[0][1],dataArr[0][2]])

所以,基本上我试图创建一个字典树,而且我不确定声明应该如何从文件中读取字典。

for word in open(inputFile):
    word = word.rstrip()
    if len(word) not in dictionary:
        dictionary[len(word)] = {}

    for x in len(word):
        if(x == 0):
            if word[x] not in dictionary[len(word)]:
                dictionary[len(word)][word[x]] = {}

那时我意识到我被卡住了,但我不知道如何修复它,因为每个级别都会添加dictionary[len(word)][word[x-2]][word[x-1]][word[x]]。另外,我必须专门匹配每个x号码,而且我不知道会有多少个字母。我想我可以把代码编写到50但这看起来不是正确的事情。

有什么建议吗?

0 个答案:

没有答案
相关问题