Convert List to Nested Dictionary

How to convert list to nested dictionary?

For instance:

 l = [1, 2, 3, 4] 

I would like to convert it to a dictionary that looks like this:

 {1: {2: {3: {4: {}}}}} 
+5
source share
4 answers

To do this, cancel the list, then start creating an empty dictionary element.

 l = [1, 2, 3, 4] d = {} for i in reversed(l): d = {i: d} >>> print(d) {1: {2: {3: {4: {}}}}} 
+7
source

You can also use functools.reduce .

 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 construction flow looks something like

 {4: {}} -> {3: {4: {}} -> {2: {3: {4: {}}}} -> {1: {2: {3: {4: {}}}}} 

how reduce traverses the reverse iterator, creating a new singleton dict.

+4
source

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 by 0.4 s]

+1
source

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]) # {1: {2: {3: {4: {}}}}} make_nested_dict([1, 2, 3, 4], [5, 6]) # {1: {2: {3: {4: {}}}}, 5: {6: {}}} 

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]) # {1: {2: {3: {4: {}}, 7: {8: {}}}}, 5: {6: {}}} 

Visually:

 1 → 2 → 3 → 4 (A) 5 → 6 (B) \ 7 → 8 (C) 
0
source

Source: https://habr.com/ru/post/1265195/


All Articles