Convert Lists to Nested Dictionary in Python

A nested dictionary is a dictionary that contains other dictionaries as values. Converting lists to nested dictionaries is useful for organizing hierarchical data structures. Python provides several approaches including loops, the reduce() function, dictionary comprehension, and recursion.

Using for Loop

The simplest approach uses a for loop to iterate through a list and create nested dictionaries ?

my_list = ['a', 'b', 'c']

# Create empty dictionary and reference for nesting
emp_dict = p_list = {}

for item in my_list:
    p_list[item] = {}
    p_list = p_list[item]

print(emp_dict)
{'a': {'b': {'c': {}}}}

Using reduce() Function

The reduce() function from the functools module can convert lists to nested dictionaries in a functional programming style ?

from functools import reduce

data = [['P', 'Q', 'R'], ['M', 'N', 'O']]
result = [reduce(lambda x, y: {y: x}, lst[::-1]) for lst in data]

print(result)
[{'P': {'Q': 'R'}}, {'M': {'N': 'O'}}]

Using Dictionary Comprehension with zip()

Dictionary comprehension with zip() creates nested dictionaries from multiple lists ?

keys = ['Letter', 'Word', 'Number']
sub_keys = ['A', 'Box', 'Integer'] 
values = [1, 3, 41905]

# Create nested dictionary using dictionary comprehension
result = {a: {b: c} for (a, b, c) in zip(keys, sub_keys, values)}

print("The nested dictionary:", result)
The nested dictionary: {'Letter': {'A': 1}, 'Word': {'Box': 3}, 'Number': {'Integer': 41905}}

Using Recursion

Recursive functions can handle complex nested structures with arbitrary depth ?

def create_nested_dict(lst, depth=0):
    # Base case: if depth exceeds list length, return empty dict
    if depth >= len(lst[0]) if lst else True:
        return {}
    
    # Group items by current depth element
    result = {}
    for item in lst:
        if depth < len(item):
            key = item[depth]
            if key not in result:
                result[key] = []
            result[key].append(item)
    
    # Recursively create nested structure
    return {key: create_nested_dict(group, depth + 1) 
            for key, group in result.items()}

my_list = [['a', 'b', 'c'], ['a', 'b', 'd'], ['x', 'y', 'z']]
result = create_nested_dict(my_list)

print("List to Nested Dictionary:")
print(result)
List to Nested Dictionary:
{'a': {'b': {}}, 'x': {'y': {}}}

Comparison

Method Complexity Best For
For Loop Simple Linear nesting from single list
reduce() Moderate Functional programming approach
Dictionary Comprehension Simple Multiple lists with key-value pairs
Recursion Complex Arbitrary depth and complex structures

Conclusion

Use for loops for simple linear nesting, dictionary comprehension with zip() for key-value mapping, and recursion for complex hierarchical structures. Choose the method based on your data complexity and performance requirements.

Updated on: 2026-03-27T08:09:39+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements