字典字典的字符串

时间:2019-04-08 08:20:03

标签: python dictionary

嗨,我想创建一个字典的字典,但是我不能以迭代的方式输入文本…。并且我有义务创建很多变量,并且我希望字典的创建能够自动进行而无需创建变量。你能帮我改善吗?

我试图创建两个函数,并用一个单词创建此词典……

def create_last_dictionary(word, n):
dico={}
dico[word[len(word) - n]] = {}
return dico

def create_dictionary(dic_to_add, word, n):
dic = {}
dic[word[len(word) - n]]=dic_to_add
return dic

word = "mommy"

one = create_last_dictionary(word, 1) 
two = create_dictionary(one, word, 2)
three = create_dictionary(two, word, 3)
four = create_dictionary(three, word, 4)
five = create_dictionary(four, word, 5)
six = create_dictionary(five, word, 6)
seven = create_dictionary(six, word, 7)

result :
{'m': {'o': {'r': {'n': {'i': {'n': {'g': {}}}}}}}}

我想要一个像这样的单词列表: 如果列表是:[“好”,“早晨”,“妈妈”]

我希望字典为:

{{'g': {'o': {'o': {'d': {}}}}}, 'm': {'o': {'m': {'m': {'y': {}}}}, {'r': {'n': {'i': {'n': {'g': {}}}}}}}}

the representation of the dictionary :
{
 {'g': {'o': {'o': {'d': {}}}}}, 
 {'m': {'o': {{'m': {'m': {'y': {}}}}, 
              {'r': {'n': {'i': {'n': {'g': {}}}}}}}}}
 }

2 个答案:

答案 0 :(得分:1)

您需要创建一个函数,以便在现有(可能是空的)树中插入新单词。为此,我提出了一个递归函数:

def insert(tree, path):
  if path:
    insert(tree.setdefault(path[0], {}), path[1:])

现在您可以使用它:

tree = {}
insert(tree, 'good')
insert(tree, 'morning')
insert(tree, 'mommy')
print(tree)

打印

{'m': {'o': {'m': {'m': {'y': {}}},
             'r': {'n': {'i': {'n': {'g': {}}}}}}},
 'g': {'o': {'o': {'d': {}}}}}

编辑:

如果您不喜欢使用.setdefault()(因为它似乎很难理解),请考虑以下事项:

def insert(tree, path):
  if path:
    if path[0] not in tree:
      tree[path[0]] = {}
    insert(tree[path[0]], path[1:])

答案 1 :(得分:0)

您可以创建一个递归函数来代替链接函数调用;您已经创建了两个案例,您就快到了。我在这里找到了有关Python递归函数的课程:https://www.python-course.eu/python3_recursive_functions.php