How can I convert a list
into nested `dictionary\'?
For example:
l = [1, 2, 3, 4]
I\'d like to convert it to a dictio
You could also use functools.reduce for this.
reduce(lambda cur, k: {k: cur}, reversed(l), {})
Demo
>>> from functools import reduce
>>> l = [1, 2, 3, 4]
>>> reduce(lambda cur, k: {k: cur}, reversed(l), {})
{1: {2: {3: {4: {}}}}}
The flow of construction looks something like
{4: {}} -> {3: {4: {}} -> {2: {3: {4: {}}}} -> {1: {2: {3: {4: {}}}}}
as reduce
traverses the reverse iterator making a new single-element dict.