[Rod Stephens Books]
Index Books Python Examples About Rod Contact
[Mastodon] [Bluesky] [Facebook]
[Build Your Own Python Action Arcade!]

[Build Your Own Ray Tracer With Python]

[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

Title: Parse hierarchical data from a string in Python

[This program parses hierarchical data from a string and displays its JSON equivalent]

In the next few posts, I'm going to describe some handy features of the tkinter Treeview widget, which can display hierarchical data. That begs the question, "How do you load hierarchical data?"

One precise way to define hierarchical data in a program is to use a hierarchical data language like JSON, XML, or YAML. Unfortunately, those languages aren't super intuitive for non-programmers. If you're writing the program for your own use, that's not a problem (because I know you're smart), but it can be an issue if you have users who need to define the data.

Those languages are also pretty verbose if you have simple data needs.

This example shows how you can use Python to parse simple hierarchical data. Later posts will show how you can display that data in tkinter's Treeview widget.

Visualizing Sample Data

Here's some hierarchical data for a company org chart written as simple text. Indentation shows which people report to which managers.

Snort & Giggle, LLC. Anita Nap — Chief Executive Officer (CEO) Justin Case — VP of Risk & Overthinking May B. Later — Director of Procrastination Al Dente — Senior Deadline Stretcher Paige Turner — Intern, Unread Memos Brock Lee — Lead Burnout Prevention Specialist Bea Minor — VP of Low-Key Operations Stan Dupp — Director of Endless Meetings Carrie Oakey — Morale & Karaoke Coordinator Tim Burr — Specialist, Falling Asleep on Zoom Ella Vator — Manager of Escalations Robin Banks — Chief Financial Officer (CFO) Bill Ding — Director of Overhead Costs Penny Less — Junior Budget Analyst

This format is intuitive enough that users should be able to understand how it works and edit it if necessary. Here's part of this data in JSON format.

[ { "name": "Snort & Giggle, LLC.", "children": [ { "name": "Anita Nap", "title": "Chief Executive Officer (CEO)", "children": [ { "name": "Justin Case", "title": "VP of Risk & Overthinking", "children": [ { "name": "May B. Later", "title": "Director of Procrastination", "children": [ { "name": "Al Dente", "title": "Senior Deadline Stretcher", "children": [] }, { "name": "Paige Turner", "title": "Intern, Unread Memos", "children": [] } ] }, ...

You and I can read this, but it would be pretty confusing to the average user. This version is also much longer than the original. The original data uses 15 lines of text while the JSON version is 83 lines long.

No matter how you store the data, you'll need to be able to load it into Python objects. If you use a language like JSON, XML, or YAML, you can use libraries to load the data. For the indented data this example uses, you need to write your own function.

Using a Stack

Here's the general approach used by this example. The function uses each line of data to create a node to go in the tree of data. It uses the number of spaces at the beginning of the line to get the node's level in the hierarchy.

The only thing we need to figure out is which node in the tree is the new node's parent. For example, look at the data shown earlier and suppose we're reading the line for Bea Minor. The program needs to find the node for Anita Nap so it can add Bea's node as a child of Anita's node. More precisely, it must add Bea's node to Anita's node's children list.

To do that, the program uses a stack to keep track of the ancestors above the most recently added node. In this example, when the function is looking at Bea's data, the most recently added node is Brock Lee, so the stack would hold:

Snort & Giggle, LLC. Anita Nap Justin Case Brock Lee

When it considers Bea's node, it looks back through the stack to find an ancestor with level less than the new node's level. Bea's node is at level 2 (it is indented 2 levels). Here are the ancestors again with the levels added:

0: Snort & Giggle, LLC. 1: Anita Nap 2: Justin Case 3: Brock Lee

So in this example, the function pops nodes off of the stack until it finds a node with level less than 2. That is Anita's node, which has level 1, so the function adds Bea's node as a child of Anita's node. It also adds Bea's node to the ancestor stack to get this new stack state:

0: Snort & Giggle, LLC. 1: Anita Nap 2: Bea Minor

That's the general approach. The following section describes the function that does all this.

Writing the Function

The following parse_indented_tree function parses the indented string in its text parameter.

def parse_indented_tree(text, indent_size=4): '''Load tree data from indented text.''' # A list for the top-level roots. roots = [] # The ancestors stack holds tuples (level, node). ancestors = [] for line in text.splitlines(): # Skip blank lines. if not line.strip(): continue # Find the line's level. level = (len(line) - len(line.lstrip(' '))) // indent_size line = line.strip() # Split name and title if there's a dash. if '—' in line: name, title = line.split('—', 1) new_node = {'name': name.strip(), 'title': title.strip(), 'children': []} else: new_node = {'name': line.strip(), 'children': []} # Pop the ancestors until we find the new node's parent with level - 1. while ancestors and ancestors[-1][0] >= level: ancestors.pop() # If we found a parent, attach it there. Otherwise it's a root. if ancestors: ancestors[-1][1]['children'].append(new_node) else: roots.append(new_node) # Push the new node onto the ancestors stack. ancestors.append((level, new_node)) # Return the list of roots. return roots

The hierarchy could have multiple root nodes with level 0, so the function first creates a roots list to hold them. It then initializes the ancestors stack to be empty.

Next, the function splits text into lines and loops through the lines.

If a line is blank, the code continues the loop to skip that line. That lets you add blank lines to the text to make it more readable. (Normally I would also consider ignoring comments beginning with #, but this is complicated enough for now.)

To calculate the new line's level, the code takes the line's length, subtracts its length without leading spaces, and divides the result by the indent size. (In fact, you don't really need to divide by the indent size. I'll let you ponder the result if you don't.)

Next, the code looks for a - character. If the line contains a -, it splits the line into a name and title. You could parse the line further if it contains other application-specific information like employee IDs, phone number, of what have you.

The function then creates a new node to store the line's data. The node is a dictionary holding the name, possibly a title, and an empty children list.

At this point, the code uses a while loop to look back through the ancestors stack to find the most recent ancestor with level smaller than the new node's level. As long as the ancestors stack is not empty and the most recent ancestor node has level greater than or equal to the current node's level, the code pops the most recent node off the stack.

If the function finds the new node's parent, it adds the new node to that parent's children list. If it did not find a parent node, this is a top level node so the function adds it to the roots list.

The code then adds the new node to the ancestors stack so it can be the parent for later nodes.

After the function has processed all of the lines, it returns the list of roots.

Using the Function

When it starts, the program calls the following load_org_data function to load the sample data.

def load_org_data(): '''Load the hierarchical org data.''' org_data = ''' Snort & Giggle, LLC. Anita Nap — Chief Executive Officer (CEO) Justin Case — VP of Risk & Overthinking May B. Later — Director of Procrastination Al Dente — Senior Deadline Stretcher Paige Turner — Intern, Unread Memos Brock Lee — Lead Burnout Prevention Specialist Bea Minor — VP of Low-Key Operations Stan Dupp — Director of Endless Meetings Carrie Oakey — Morale & Karaoke Coordinator Tim Burr — Specialist, Falling Asleep on Zoom Ella Vator — Manager of Escalations Robin Banks — Chief Financial Officer (CFO) Bill Ding — Director of Overhead Costs Penny Less — Junior Budget Analyst ''' return parse_indented_tree(org_data)

This code defines a triple-quoted string containing the hierarchical data and passes it to the parse_indented_tree function.

The following code shows how the program tests this code.

... # Load the org chart data. org_data = load_org_data() # Build the UI. self.build_ui() # Display the hierarchy as JSON. self.data_text.insert('1.0', json.dumps(org_data, indent=4)) ...

After some setup, the program calls load_org_data to load the data. It then calls self.build_ui to create the tkinter user interface.

Next, the program uses json.dumps to convert the hierarchical data into a JSON string and displays it in the ScrolledText widget named data_text.

Conclusion

The parse_indented_tree function lets you easily parse hierarchical data from an indented string. If this was a real application, I would probably store the data in a text file rather than embedding the data in the application. I'll leave that for an exercise.

In my next few posts, I'll use the hierarchical data to demonstrate the Treeview widget. Meanwhile, download the example to experiment with it and to see additional details.

© 2025 - 2026 Rocky Mountain Computer Consulting, Inc. All rights reserved.