How convert list to nested dictionary?

Alexander Gattin xrgtn at umc.com.ua
Thu Nov 11 03:36:02 EST 2010


Hello,

On Thu, Nov 04, 2010 at 02:10:12PM -0700, macm
wrote:
> > > How convert list to nested dictionary?
> >
> > >>>> l
> > > ['k1', 'k2', 'k3', 'k4', 'k5']
> > >>>> result
> > > {'k1': {'k2': {'k3': {'k4': {'k5': {}}}}}}
>
> http://www.amk.ca/python/writing/functional

so, why didn't you try python's reduce?

IMO this is trivial:
> >>> l
> ['k1', 'k2', 'k3', 'k4', 'k5']
> >>> reduce(lambda x,y: {y:x}, l.__reversed__())
> {'k1': {'k2': {'k3': {'k4': 'k5'}}}}
> >>> reduce(lambda x,y: {y:x}, l.__reversed__(), dict())
> {'k1': {'k2': {'k3': {'k4': {'k5': {}}}}}}
> >>> 

second reduce uses empty dict for seed.

-- 
With best regards,
xrgtn



More information about the Python-list mailing list