2017-03-08 107 views
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 

我在這裏找不到重複的問題,如果存在我找不到的地方,我會先道歉。任何幫助是極大的讚賞。

+1

唯一的區別是,它和愚蠢(從3小時前...(_same class?;)_))是你必須拆分你的列表,而不是使用初始化。類似'reduce(lambda x,y:{y:x},reversed(inputSentence.strip('。')。split()))'。這裏還有一個非「減少」的解決方案。我也會假設你實際上不需要使用遞歸,因爲你沒有嘗試。 – miradulo

回答

0

你可以做這樣的事情:

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

curdict只指向輸出詞典的位置。