How convert list to nested dictionary?

Chris Rebert clp2 at rebertia.com
Thu Nov 4 17:32:59 EDT 2010


> On 4 nov, 16:53, Chris Rebert <c... at rebertia.com> wrote:
>> On Thu, Nov 4, 2010 at 11:48 AM, macm <moura.ma... at gmail.com> wrote:
>> > Hi Folks
>>
>> > How convert list to nested dictionary?
>>
>> >>>> l
>> > ['k1', 'k2', 'k3', 'k4', 'k5']
>> >>>> result
>> > {'k1': {'k2': {'k3': {'k4': {'k5': {}}}}}}
>>
>> We don't do homework.
>> Hint: Iterate through the list in reverse order, building up your
>> result. Using reduce() is one option.

On Thu, Nov 4, 2010 at 2:10 PM, macm <moura.mario at gmail.com> wrote:
> Thanks for your hint.
<snip>
> Do you have good links or books to me learn "Functional Programming"?

Relevant to the particular problem you posed:
http://en.wikipedia.org/wiki/Fold_(higher-order_function)

<snip>
> Show me, please! if you can.

I will give you this further hint:

def reducer(accumulator, elem):
    # if accumulator = {'k5': {} }
    # and elem = 'k4'
    # then we want to return {'k4': {'k5': {} } }
    now_implement_me()

l = ['k1', 'k2', 'k3', 'k4', 'k5']
result = reduce(reducer, reversed(l), {})

Note that:
reduce(reducer, reversed(l), {})
Is basically equivalent to:
reducer( reducer( reducer( reducer( reducer({}, 'k5'), 'k4'), 'k3'),
'k2'), 'k1')

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list