recursion - python recursive in multiple dict -


i have problem multiple dict in recursive , origin non-recursive code

mylist = (["aa","bb","cc","dd"]) tempdict = dict() n = len(mylist) j in range(0 , n ):     if j == 0:         if mylist[j] not in tempdict:             tempdict[mylist[j]] = "1"     if j == 1:         if mylist[j] not in tempdict[mylist[0]]:             tempdict[mylist[0]] = dict()             tempdict[mylist[0]][mylist[1]] = "1"     if j == 2:         if mylist[j] not in tempdict[mylist[0]][mylist[1]]:             tempdict[mylist[0]][mylist[1]] = dict()              tempdict[mylist[0]][mylist[1]][mylist[2]] = "1"     if j == 3:         .......     if j == 4:         .......     if j == n:         ....... print tempdict 

result : {'aa' {'bb': {'cc': {'dd': '1'}}}} , work when need build multiple key dict(). , impossible list all. refine code in recursive function

def rfun(tmpdict, mylist, idx, listlen):     if idx < listlen:         if idx == 0:             if mylist[idx] not in tmpdict:                 tmpdict[mylist[idx]] = "1"             rfun(tmpdict [mylist[idx]], list, idx + 1, listlen)         else:             if list[idx] not in tmpdict:                 tmpdict = dict()                 tmpdict [mylist[idx]] = "1"             rfun(tmpdict [mylist[idx]], mylist, idx + 1, listlen)  newdict = dict() mylist = (["aa","bb","cc","dd"] print rfun(newdict, mylist, 0, len(mylist)) 

result : {'aa':'1'}

but , result not in expect ,
please me find wrong in recursive code , all.

here go.

def rfun(tmpdict, mylist, idx, listlen):     if idx < listlen:         if idx == listlen - 1: # last element in mylist             tmpdict[mylist[idx]] = "1"         else:             tmpdict[mylist[idx]] = {}             rfun(tmpdict[mylist[idx]], mylist, idx + 1, listlen)  newdict = {} mylist = ["aa","bb","cc","dd"] rfun(newdict, mylist, 0, len(mylist)) print newdict 

the key idea pass newly create dictionary next recursive function call if element not last one.


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -