On May 28, 3:11 am, Peter Otten <[EMAIL PROTECTED]> wrote: > Gary Herron wrote: > > Alok Kumar wrote: > >> Dear All, > > >> I am using dictionary for filling my xpath parsed data. > > >> I wanted to use in the following manner. > > >> mydict[index] ["key1"] ["key2"] #Can someone help me with right > >> declaration. > > >> So that I can fill my XML xpath parsed data > > >> mydict[0] ["person"] ["setTime"] = "12:09:30" > >> mydict[0] ["person"] ["clrTime"] = "22:09:30" > > [I didn't see the original post] > > >>> from collections import defaultdict > >>> def make_inner(): > > ... return defaultdict(lambda: defaultdict(make_inner)) > ...>>> mydict = make_inner() > >>> mydict[0]["person"]["setTime"] = "12:09:30" > >>> mydict[0]["person"]["shoes"]["color"] = "bright yellow" > >>> mydict > <snip>
When this has come up in previous threads, I think this was the best solution that was proposed: from collections import defaultdict class recursivedefaultdict(defaultdict): def __init__(self): self.default_factory = type(self) Here is this recursivedefaultdict in action: data = [ ('A','B','Z',1), ('A','C','Y',2), ('A','C','X',3), ('B','A','W',4), ('B','B','V',5), ('B','B','U',6), ('B','D','T',7), ] table = recursivedefaultdict() for k1,k2,k3,v in data: table[k1][k2][k3] = v for kk in sorted(table.keys()): print "-",kk for jj in sorted(table[kk].keys()): print " -",jj for ii in sorted(table[kk][jj].keys()): print " -",ii,table[kk][jj][ii] Prints: - A - B - Z 1 - C - X 3 - Y 2 - B - A - W 4 - B - U 6 - V 5 - D - T 7 -- Paul -- http://mail.python.org/mailman/listinfo/python-list