Reputation: 29
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.
Upvotes: 0
Views: 287
Reputation: 55
mylist = ["AA","BB","CC","DD"]
A recursive version is concise, but in extreme cases could cause stack overflow:
def l2rd(*args):
return { args[0] : (len(args)>1) and l2rd(*args[1:]) or "1" }
result = l2rd(*mylist)
print(result)
Result: {'AA': {'BB': {'CC': {'DD': '1'}}}
A non-recursive version could do the same thing by looping over the list in reverse order and doing something like:
curr = "1"
for key in reversed_list:
curr = { key : curr }
return curr
But that requires copying the list in order to reverse it (which should still be more efficient than recursion). Iteration via index would also work using range(len(args)-1,-1,-1)
Upvotes: 1
Reputation: 265
Here you go.
def rfun(tmpdict, mylist, idx, listlen):
if idx < listlen:
if idx == listlen - 1: # for 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 is to pass the newly create dictionary to next recursive function call if the element is not the last one.
Upvotes: 1