Fun transformation problem

Tim Leslie tim.leslie at gmail.com
Thu Aug 26 12:27:00 EDT 2004


This is what I came up with. It's recursive, so it could get you into
trouble with longer lists, but hey, it's late at night and it'll do
for now :-)

def g(d, lst):
    head = lst[0]
    tail = lst[1:]
    if not tail:
        return head
    else:        
        d[head] = g(d.get(head, {}), tail)
    return d

def f(lst):
    d = {}
    for xs in lst:
        d = g(d, xs)
    return d

Cheers,

Tim

On Thu, 26 Aug 2004 18:20:23 +0400, anton muhin <antonmuhin at rambler.ru> wrote:
> 
> 
> 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.
> 
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list