0
我有一个问题,我一直在尝试理清。我有一个字符串需要被转换为嵌套字典,其中的键和值基于字符串中的相邻字。这里有一个例子:从字符串递归创建一个嵌套字典
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()))'。这里还有一个非“减少”的解决方案。我也会假设你实际上不需要使用递归,因为你没有尝试。 – miradulo