Open In App

Convert a List of Lists into Tree-like Dict - Python

Last Updated : 22 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a list of lists we need to convert it into tree-like dictionary. For example we are given a list of list li = [["a", "b", "c"], ["a", "b", "d"], ["x", "y"]] we need to convert it into tree like dict so that the output should be like {'a': {'b': {'c': {}, 'd': {}}}, 'x': {'y': {}}} .We can use various approaches to do this

Using Basic Loops

To convert a list of lists into a tree-like dictionary using basic loops, iterate through the outer list and use a nested loop to traverse each inner list, creating dictionary keys at each level. Assign values at the deepest level or leave the final key with an empty dictionary as needed.

Python
# Initialize an empty dictionary to store the tree-like structure
d = {}

# Define the list of lists, where each list represents a path
li = [["a", "b", "c"], ["a", "b", "d"], ["x", "y"]]

# Iterate through each path (list) in the main list
for path in li:
  
    # Start at the root of the dictionary for each path
    current = d
  
  	# Iterate through each part (node) in the current path
    for part in path:
    
    	# If the current part is not already a key, add it with an empty dictionary as its value
        if part not in current:
            current[part] = {}
        
        	# Move to the next level in the dictionary
        current = current[part]

# Print the resulting tree
print(d)

Output
{'a': {'b': {'c': {}, 'd': {}}}, 'x': {'y': {}}}

Explanation:

  • Outer loop iterates through each sublist in li, treating each as a "path," while the nested loop traverses each part of the path, ensuring keys are added to the dictionary at each level if they don't already exist.
  • At the deepest level of each path, the dictionary structure branches out, resulting in a tree-like hierarchy, where keys represent nodes and values are nested dictionaries

Using Sorted Input and Itertools

Using itertools.groupby along with sorted, group consecutive elements from a sorted input, creating subgroups based on the first element. This allows for efficient processing of sorted data and enables handling grouped elements without explicitly checking conditions.

Python
from itertools import groupby  # Import groupby from itertools module to group elements

# Initialize an empty dictionary to store the tree-like structure
d = {}

# Define the list of paths to create the tree-like structure
li = [["a", "b", "c"], ["a", "b", "d"], ["x", "y"]]

# Sort the input list and group elements by the first element of each sublist
for key, group in groupby(sorted(li), lambda x: x[0]):
    
  	# Create a list of the remaining parts of the path (excluding the first element)
    subtree = [item[1:] for item in group if len(item) > 1]
    
    # Initialize an empty dictionary at the root of the tree for the current key
    d[key] = {}
    
    # Set the current level to the root of the current subtree
    current = d[key]
    
    # Iterate through the sub-paths and build the nested dictionary structure
    for path in subtree:
        for part in path:
            
            # If the part does not exist, create a new dictionary at that level
            if part not in current:
                current[part] = {}
            
            # Move to the next level in the nested structure
            current = current[part]

# Convert defaultdict to a regular dict for better readability and print the result
print(dict(t))

Output
{'a': {'b': {'c': {'b': {'d': {}}}}}, 'x': {'y': {}}}

Explanation:

  • Code sorts the input list li, then uses groupby to group sublists by their first element, creating separate subtrees for each group, and constructs the nested dictionary structure for each group.
  • For each group, it iterates through the remaining parts of the path (after the first element) and builds a tree-like structure by creating new dictionaries as necessary, ultimately printing the fully constructed tree.

Manually Iterating with Nested Dictionaries

Manually iterating with nested dictionaries involves traversing through each level using a loop, accessing each key-value pair and iterating over deeper levels as needed. This allows for manual control of data processing at each nested dictionary level.

Python
# Initialize an empty dictionary to store the tree-like structure
d = {}

# Define the list of paths to create the tree-like structure
li = [["a", "b", "c"], ["a", "b", "d"], ["x", "y"]]

# Iterate through each path (list) in the input list
for path in li:
    # Start at the root of the dictionary for each path
    current = d
    # Iterate through each part (node) in the current path
    for part in path:
        # If the current part does not exist in the current level, create a new dictionary for it
        if part not in current:
            current[part] = {}
        # Move to the next level in the dictionary
        current = current[part]

print(dict(t))  

Output
{'a': {'b': {'c': {}, 'd': {}}}, 'x': {'y': {}}}

Explanation:

  • Code iterates through each list in li, and for each path, it traverses or creates nested dictionaries at each level, ensuring that keys represent nodes in the tree structure.
  • After processing each path, it prints the fully constructed tree-like dictionary, where each path is represented by a series of nested dictionaries.

Next Article
Practice Tags :

Similar Reads