Convert a List of Lists into Tree-like Dict - Python
Last Updated :
22 Jan, 2025
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.
Similar Reads
Python - Convert a list into tuple of lists When working with data structures in Python, there are times when we need to convert a list into a tuple of smaller lists.For example, given a list [1, 2, 3, 4, 5, 6], we may want to split it into a tuple of two lists like ([1, 2, 3], [4, 5, 6]). We will explore different methods to achieve this con
3 min read
Python - Convert List to List of dictionaries We are given a lists with key and value pair we need to convert the lists to List of dictionaries. For example we are given two list a=["name", "age", "city"] and b=[["Geeks", 25, "New York"], ["Geeks", 30, "Los Angeles"], ["Geeks", 22, "Chicago"]] we need to convert these keys and values list into
4 min read
Python | Convert list into list of lists Given a list of strings, write a Python program to convert each element of the given list into a sublist. Thus, converting the whole list into a list of lists. Examples: Input : ['alice', 'bob', 'cara'] Output : [['alice'], ['bob'], ['cara']] Input : [101, 202, 303, 404, 505] Output : [[101], [202],
5 min read
Convert List of Lists to Dictionary - Python We are given list of lists we need to convert it to python . For example we are given a list of lists a = [["a", 1], ["b", 2], ["c", 3]] we need to convert the list in dictionary so that the output becomes {'a': 1, 'b': 2, 'c': 3}. Using Dictionary ComprehensionUsing dictionary comprehension, we ite
3 min read
Python | Convert list of tuples into list In Python we often need to convert a list of tuples into a flat list, especially when we work with datasets or nested structures. In this article, we will explore various methods to Convert a list of tuples into a list. Using itertools.chain() itertools.chain() is the most efficient way to flatten a
3 min read