【发布时间】: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