# Fun transformation problem

Dale Strickland-Clark dale at riverhall_nospam_.co.uk
Thu Aug 26 15:54:54 CEST 2004

```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

```