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

Given a nested list, we want to convert it to a dictionary whose elements represent a tree data structure. In this article, we will explore two approaches to transform a list of lists into a hierarchical dictionary structure.

Using Simple Iteration and Slicing

We reverse the items in each list using slicing and then build the tree structure by checking and adding keys at each level ?

Example

def create_tree(nested_list):
    new_tree = {}
    for list_item in nested_list:
        current_tree = new_tree
        
        for key in list_item[::-1]:
            if key not in current_tree:
                current_tree[key] = {}
            current_tree = current_tree[key]
    return new_tree

# Given list
data = [['X'], ['Y', 'X'], ['Z', 'X'], ['P', 'Z', 'X']]
result = create_tree(data)
print(result)

The output of the above code is −

{'X': {'Y': {}, 'Z': {'P': {}}}}

Using reduce() and getitem()

We use the functools and operator modules to get the functions reduce and getitem. This approach creates helper functions to navigate and set items in the tree structure ?

Example

from functools import reduce
from operator import getitem

def get_tree_node(tree, path):
    return reduce(getitem, path, tree)

def set_tree_node(tree, path):
    get_tree_node(tree, path[:-1])[path[-1]] = dict()

# Given list
data = [['X'], ['Y', 'X'], ['Z', 'X'], ['P', 'Z', 'X']]
tree = {}

for item in data:
    set_tree_node(tree, item[::-1])

print(tree)

The output of the above code is −

{'X': {'Y': {}, 'Z': {'P': {}}}}

How It Works

Both methods reverse each list using [::-1] slicing to process elements from deepest to shallowest level. The first method uses simple iteration, while the second uses functional programming with reduce() to navigate the tree structure.

Comparison

Method Complexity Best For
Simple Iteration Easy to understand Beginners, readable code
reduce() + getitem() Functional approach Advanced users, concise code

Conclusion

Both approaches effectively convert a list of lists into a tree-like dictionary structure. The simple iteration method is more readable, while the functional approach using reduce() provides a more concise solution for experienced Python developers.

Updated on: 2026-03-15T18:34:06+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements