Here is the abstraction. Usage for setdefault usually overshadowed by defaultdict , but here is an interesting application if you have one or more lists (iterations):
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])
Nested branches
Unlike defaultdict , this method accepts duplicate keys, adding to existing "branches". For example, we add a new branch 7 → 8 at the third level of the first branch (A):
ABC make_nested_dict([1, 2, 3, 4], [5, 6], [1, 2, 7, 8])
Visually:
1 → 2 → 3 → 4 (A) 5 → 6 (B) \ 7 → 8 (C)
source share