- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Convert a list of lists into tree-like dict
Given a nested list we want to convert it to a dictionary whose elements can be considered as part of a tree data structure. In this article we will see the two approaches to convert a nested list into to add dictionary whose elements represent a tree like data structure.
Using Slicing
We reverse the items in the list aby slicing and then check if the item is present in the list. If it is not present we ignore it else we add it to the tree.
Example
def CreateTree(lst): new_tree = {} for list_item in lst: currTree = new_tree for key in list_item[::-1]: if key not in currTree: currTree[key] = {} currTree = currTree[key] return new_tree # Given list listA = [['X'], ['Y', 'X'], ['Z', 'X'], ['P', 'Z', 'X']] print(CreateTree(listA))
Running the above code gives us the following result −
Output
{'X': {'Y': {}, 'Z': {'P': {}}}}
Using reduce and getitem
We use the functools and operator module to get the functions reduce and getitem. Using these functions we define two functions to get the items from the list and set the items into a tree structure. Here also we use the slicing approach to reverse the elements of the list and then apply the two created functions to create the dictionaries whose elements are in tree structure.
Example
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() # Given list lst = [['X'], ['Y', 'X'], ['Z', 'X'], ['P', 'Z', 'X']] tree = {} for i in lst: setTree(tree, i[::-1]) print(tree)
Running the above code gives us the following result −
Output
{'X': {'Y': {}, 'Z': {'P': {}}}}