i have a problem with multiple dict in recursive , the origin non-recursive code is
mylist = (["AA","BB","CC","DD"])
tempdict = dict()
n = len(mylist)
for 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'}}}} and it is work when i need build a multiple key by dict(). however , it is impossible to list all. so i would like to refine code in a 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 , the result is not in my expect ,
please help me to find what is wrong in my recursive code ,
thanks all.