【问题标题】:Recursively create a nested dictionary from string [duplicate]从字符串递归创建嵌套字典[重复]
【发布时间】:2017-03-08 20:46:09
【问题描述】:

我有一个问题一直在尝试解决。我有一个字符串需要转换为嵌套字典,其中的键和值基于字符串中的相邻单词。这是一个例子:

graphMaster = {}
inputSentence = "I have a dog named Max."

我想获取这个字符串,并将其转换为类似于以下输出的字典:

print graphMaster
{'I': {'have': {'a': {'dog': {'named': 'Max'}}}}}

我尝试了以下方法:

graphMaster = {}
inputSentence = "I have a dog named Max."
while True:
    inputList = inputSentence.strip().split(' ')
    for currentIndex, word in enumerate(inputList):
        nextIndex = currentIndex + 1
        if nextIndex < len(inputList):
            if word not in graphMaster.keys():
                graphMaster[word] = inputList[nextIndex]
            elif word in graphMaster.keys():
                break
print graphMaster

我在这里找不到重复的问题,如果存在我找不到的问题,我预先道歉。非常感谢任何帮助。

【问题讨论】:

  • 这和被骗的唯一区别(从 3 小时前开始...... (same class? ;)) )是你必须拆分你的列表,而不是使用初始化程序。像reduce(lambda x, y: {y: x}, reversed(inputSentence.strip('.').split())) 这样的东西。那里还有一个非reduce 解决方案。我还将假设您实际上不需要使用递归,因为您不需要尝试。

标签: python list dictionary recursion nested


【解决方案1】:

你可以这样做:

outdict = {}
curdict = outdict
for f in inputSentence.split(' '):
    curdict[f] = {}
    curdict = curdict[f]
print outdict

curdict 仅指向输出字典中的位置。

【讨论】:

    猜你喜欢
    • 2019-06-03
    • 2019-02-08
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 2022-11-17
    • 2017-05-13
    相关资源
    最近更新 更多