我有一个问题,我一直试图理清。我有一个字符串需要转换为嵌套字典,其中键和值基于字符串中的相邻单词。这是一个例子:
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
我在这里找不到重复的问题,如果有一个我无法找到的话,我会道歉。非常感谢任何帮助。
答案 0 :(得分:0)
你可以这样做:
outdict = {}
curdict = outdict
for f in inputSentence.split(' '):
curdict[f] = {}
curdict = curdict[f]
print outdict
curdict
仅指向输出字典中的某个位置。