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