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
For that reverse the list, then start creating the empty dictionary element.
l = [1, 2, 3, 4]
d = {}
for i in reversed(l):
d = {i: d}
>>> print(d)
{1: {2: {3: {4: {}}}}}
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.
You can do something like this:
l = [1,2,3,4]
d = {}
for i in l[::-1]:
d = {i: d}
print(d)
{1: {2: {3: {4: {}}}}} [Finished in 0.4s]
Here is an abstraction. Uses for setdefault
are typically overshadowed by defaultdict
, but here is an interesting application if you have one or more lists (iterables):
def make_nested_dict(*iterables):
"""Return a nested dictionary."""
d = {}
for it in iterables:
temp = d
for i in it:
temp = temp.setdefault(i, {})
return d
make_nested_dict([1, 2, 3, 4])
# {1: {2: {3: {4: {}}}}}
make_nested_dict([1, 2, 3, 4], [5, 6])
# {1: {2: {3: {4: {}}}}, 5: {6: {}}}
Nested Branches
Unlike defaultdict
, this technique accepts duplicate keys by appending to existing "branches". For example, we will append a new 7 → 8
branch at the third level of the first (A) branch:
A B C
make_nested_dict([1, 2, 3, 4], [5, 6], [1, 2, 7, 8])
# {1: {2: {3: {4: {}}, 7: {8: {}}}}, 5: {6: {}}}
Visually:
1 → 2 → 3 → 4 (A) 5 → 6 (B)
\
7 → 8 (C)