Fun transformation problem

anton muhin antonmuhin at rambler.ru
Thu Aug 26 10:20:23 EDT 2004


Dale Strickland-Clark wrote:
> A guy in the office has come up with this interesting transformation
> problem. We have a solution but I'm sure there's a neater, more 'pythonic' 
> approach.
> 
> I thought this might appeal to some here:
> 
> I want a function to convert a list of tuples into a hierarchy of
> dictionaries.  Let me first demonstrate with an example:
> 
> 
>>>>lstA = [(1, 2, 3), (1, 3, 4), (2, 5, 6)]
>>>>dctA = fncA(lstA)
>>>>print dctA
> 
> {1: {2: 3, 3: 4}, 2: {5: 6}}
> 
> 
> I essentially want the definition to fncA.  Here is another example:
> 
> 
>>>>lstA = [(1, 2, 3, 4) ,(3, 4, 5, 6), (3, 4, 6, 7), (3, 4, 6, 8), (3, 4,
> 
> 5, 1), (3, 4, 7, 9)]
> 
>>>>dctA = fncA(lstA)
>>>>print dctA
> 
> {1: {2: {3: 4}}, 3: {4: {5: 1, 6: 8, 7: 9}}}
> 
> 
> Each tuple in the original list must be unique after the last value is
> excluded (since these values are used to form the "hierarchical key".
> 
> I have written a function, which seems to work but looks very cumbersome.
> Could anyone point me to a simpler solution?
> 
> 
> 
> Dale Strickland-Clark
> Riverhall Systems

The following:

def transform(l):
   d = {}

   for t in l:
     c = d
     for e in t[:-2]:
       c = c.setdefault(e, {})
     c[t[-2]] = t[-1]

   return d

seems clear enough for me.

with the best regards,
anton.



More information about the Python-list mailing list