Python | Convert a list of lists into tree-like dict

Given a list of lists, write a Python program to convert the given list of lists into a tree-like dictionary.

Examples:

Input : [[1], [2, 1], [3, 1], [4, 2, 1], [5, 2, 1], [6, 3, 1], [7, 3, 1]]
Output : {1: {2: {4: {}, 5: {}}, 3: {6: {}, 7: {}}}}

Input : [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']]
Output : {'A': {'C': {'D': {}}, 'B': {}}}

 
Method #1 : Naive Method
This is a Naive approach in which we use two for loops to traverse the list of lists. We initialize the empty dictionary ‘tree’ to currTree and each time we check if the key (list of list’s item) is included in the currTree or not. If not, include it in the currTree, otherwise do nothing. Finally, assign the currTree[key] to currTree.



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to Convert a list
# of lists into Dictionary (Tree form)
  
def formTree(list):
    tree = {}
    for item in list:
        currTree = tree
  
        for key in item[::-1]:
            if key not in currTree:
                currTree[key] = {}
            currTree = currTree[key]
              
    return tree
  
# Driver Code
lst = [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']]
print(formTree(lst))

chevron_right


Output:

{'A': {'B': {}, 'C': {'D': {}}}}

 
Method #2 : Using reduce()
The reduce() function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. We will use reduce() to traverse the dictionary and reuse getTree() to find the location to store the value for setTree(). All but the last element in mapList is needed to find the ‘parent’ dictionary to add the value to, then use the last element to set the value to the right key.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to Convert a list
# of lists into Dictionary (Tree form)
  
from functools import reduce
from operator import getitem
  
def getTree(tree, mappings):
    return reduce(getitem, mappings, tree)
      
def setTree(tree, mappings):
    getTree(tree, mappings[:-1])[mappings[-1]] = dict()
  
# Driver Code
lst = [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']]
tree ={}
for item in lst:
    setTree(tree, item[::-1])
  
print(tree)

chevron_right


Output:

{'A': {'B': {}, 'C': {'D': {}}}}


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.