How to create tree structure from hierarchical data in Python?

2024/11/20 2:37:11

Hi I am a bit new to Python and am a bit confused how to proceed. I have a large dataset that contains both parent and child information. For example, if we have various items and their components, and their components also have other components or children, how do we create a type of tree structure? Here is an example of the data: enter image description here

I was wondering how I can get it into a tree structure. So the output would be:

Tree structure for car

and it will also return the one for airplane, similar to the one for car.

I know that the common attribute for this would be based upon the parent number/child number. But, I am a bit confused on how to go about this in python.

Answer

Use a class to encode the structure:

class TreeNode:def __init__(self, number, name):self.number = numberself.name = nameself.children = []def addChild(self, child):self.children.append(child)

One example of how to use it:

car = TreeNode(1111, "car")
engine = TreeNode(3333, "engine")
car.addChild(engine)

Note: The number attribute doesn't have to be an int (e.g. 1111 for car); it can just as well be a string of the integer (i.e. "1111").


To actually get something resembling your desired output, we'll need to serialize the root object into nested dictionaries:

class TreeNode:def __init__(self, number, name):self.number = numberself.name = nameself.children = []def addChild(self, child):self.children.append(child)def serialize(self):s = {}for child in self.children:s[child.name] = child.serialize()return s

Now, we can get something resembling your desired output by using json.dumps:

dummy = TreeNode(None, None) # think of this as the root/tablecar = TreeNode(1111, "car")
dummy.addChild(car)engine = TreeNode(3333, "engine")
car.addChild(engine)fan = TreeNode(4312, "fan")
engine.addChild(fan)print(json.dumps(dummy.serialize(), indent=4))

prints:

{"car": {"engine": {"fan": {}}}
}
https://en.xdnf.cn/q/119883.html

Related Q&A

%conda install -c conda-forge prophet takes forever to install

Trying to install fb prophet but it takes so long, it has been running for both vscode editor for almost an hour conda install -c conda-forge prophet

How to Send 2D array through php cURL

Im working with a a distributed system where a php app sends a post request to a python app. My code is pretty straight forward:$ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CU…

Internally, is asyncio run_forever() basically a while True loop?

python asyncio run_forever or while True is similar but it is a "should I do this..." question. I am more trying to understand if the internals of python asyncio is basically a while True:...…

How do I switch from python 2.6 to 2.7 by default

How do I switch from python 2.6 to 2.7 by defaultls -l /usr/bin/python* lrwxrwxrwx 1 root root 9 Jan 27 12:36 /usr/bin/python -> python2.6 lrwxrwxrwx 1 root root 9 Jan 27 12:36 /usr/bin/python…

How to make a flat list from nested lists? [duplicate]

This question already has answers here:Flatten an irregular (arbitrarily nested) list of lists(54 answers)Closed 1 year ago.Given a nested list of integers, implement an iterator to flatten it. Each el…

Python 2.7: import performance

currently, I am importing bunch of .py files scattered across the file system via: def do_import(name):import impfp, pathname, description = imp.find_module(name)with fp:return imp.load_module(name, fp…

change first line of a file using bash

I need to change a single line in a file. It is always in the first line of the file. It looks like:h\tn0 n1 n2 n3 n4 n5 n6 n7 n8 n9 hilu cjt 1 1000000there is a tab in all gaps except …

1 to 2 matching in two dataframes with different sizes in Python/R

please help me with this problem Ive been struggling all day lol, solution in either Python or R is fine! Please help Im really stuck!!! I have two dataframes - df1 has 44 rows, df2 has 100 rows, they …

Can someone fix this? pip install intents

Im not sure why this is failing but I need help to fix it please Ive been trying to fix it for about 2 hours now and cant figure it out. I have tried to restart my computer, look it up on google etc. b…

Calculating Average Performance Measures in M/M/1 System Using SimPy

I am seeking to calculate the average waiting times, and average service times in the following M/M/1 queueing system, but I am not able to calculate the averages. It writes down to the console each cu…