python - To insert multiple dictionaries as values into a single key -


i need set of nested dictionaries in form {a:{}{b:{},{c:{}}}} a,b , c keys. have tried following code.

from collections import defaultdict def dictizestring(string,dictionary) :     while string.startswith('/'):         string = string[1:]     parts = string.split('/',1)      if len(parts)>1:         branch = dictionary.setdefault(parts[0],[dict()])         dictionary[parts[0]].append(dict())         dictizestring(parts[1], branch)     else:         if dictionary.has_key(parts[0]):             dictionary[parts[0]]=dict()         else:             dictionary[parts[0]]=[dict()]             dictionary[parts[0]].append(dict())                  d={}  dictizestring('/a/b/c/d', d) print d 

execution of code results in error ''list' object has no attribute 'setdefault''. code works first iteration(i.e a) throws above error second iteration(i.e b).

the append functionality works else section in last 6 lines of code.i tried use same logic in if case, throwing error.

try:

from collections import defaultdict def dictizestring(string,dictionary) :     while string.startswith('/'):         string = string[1:]     parts = string.split('/',1)      if len(parts)>1:         branch = dictionary.setdefault(parts[0],[dict()])         dictionary[parts[0]].append(dict())         dictizestring(parts[1], branch[1]) # <--- branch -> branch[1]     else:         if dictionary.has_key(parts[0]):             dictionary[parts[0]]=dict()         else:             dictionary[parts[0]]=[dict()]             dictionary[parts[0]].append(dict())                  d={}  dictizestring('/a/b/c/d', d) print d 

what have on line 7 statement setting default list of dictionaries, try stick function expecting dictionary.


Comments