Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8845189
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T11:40:43+00:00 2026-06-14T11:40:43+00:00

In Summary I am creating a tree structure out of a text file input

  • 0

In Summary

I am creating a tree structure out of a text file input using a function from SO question: Python file parsing: Build tree from text file. But I am able to produce my tree only by using a global variable and cannot find a way of avoiding this.

Input Data

In a file called data.txt I have the following:

Root
-A 10
-B
--B A 2
--B B 5
--B Z 9
--B X
---X 4
---Y
----Y0 67
----Y1 32
---Z 3
-C 19

Desired Result

{'B': ['B A 2', 'B B 5', 'B Z 9', 'B X'],
 'B X': ['X 4', 'Y', 'Z 3'],
 'Root': ['A 10', 'B', 'C 19'],
 'Y': ['Y0 67', 'Y1 32']}

My Code

import re, pprint
PATTERN = re.compile('^[-]+')
tree = {}

def _recurse_tree(parent, depth, source):
    last_line = source.readline().rstrip()
    while last_line:
        if last_line.startswith('-'):
            tabs = len( re.match(PATTERN, last_line).group() )
        else:
            tabs = 0
        if tabs < depth:
            break
        node = re.sub(PATTERN, '', last_line.strip())
        if tabs >= depth:
            if parent is not None:
                print "%s: %s" %(parent, node)
                if parent in tree:
                    tree[parent].append(node)
                else:
                    tree[parent] = [ node, ]
            last_line = _recurse_tree(node, tabs+1, source)
    return last_line

def main():
    inFile = open("data.txt")
    _recurse_tree(None, 0, inFile)
    pprint.pprint(tree)

if __name__ == "__main__":
    main()

The Problem

How do I get rid of the global variable tree? Everything I do seems to make the code much longer or uglier but I would like to use the function heavily and I hate depending on side-effects for the core result.

Supplement

After the answers below, I revised the code to return the tree in the following way. Is this pythonic? Returning a tuple and then tossing the first element seems inelegant.

def _recurse_tree(parent, depth, source, tree=None):
    if tree is None:
        tree = {}
    last_line = source.readline().rstrip()
    while last_line:
        if last_line.startswith('-'):
            tabs = len( re.match(PATTERN, last_line).group() )
        else:
            tabs = 0
        if tabs < depth:
            break
        node = re.sub(PATTERN, '', last_line.strip())
        if tabs >= depth:
            if parent is not None:
                print "%s: %s" %(parent, node)
                if parent in tree:
                    tree[parent].append(node)
                else:
                    tree[parent] = [ node, ]
            last_line, tree = _recurse_tree(node, tabs+1, source, tree)
    return last_line, tree

def main():
    inFile = open("data.txt")
    tmp, tree = _recurse_tree(None, 0, inFile)
    pprint.pprint(tree)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T11:40:44+00:00Added an answer on June 14, 2026 at 11:40 am

    Your tree variable is already a mutable; just pass it along with your recursive calls:

    def _recurse_tree(parent, depth, source, tree=None):
        if tree is None:
            tree = {}
    
        last_line = source.readline().rstrip()
        while last_line:
            if last_line.startswith('-'):
                tabs = len( re.match(PATTERN, last_line).group() )
            else:
                tabs = 0
            if tabs < depth:
                break
            node = re.sub(PATTERN, '', last_line.strip())
            if tabs >= depth:
                if parent is not None:
                    print "%s: %s" %(parent, node)
                    if parent in tree:
                        tree[parent].append(node)
                    else:
                        tree[parent] = [ node, ]
                last_line = _recurse_tree(node, tabs+1, source, tree)
        return last_line
    

    Alternatively, you can use a class to hold the state, it’ll be easier to then pluck the state from the instance:

    class TreeBuilder(object):
        _PATTERN = re.compile('^[-]+')
    
        def __init__(self, source):
            self.tree = {}
            self.source = source
            self._recurse_tree()
    
        def _recurse_tree(self, parent=None, depth=0):
             last_line = self.source.readline().rstrip()
             while last_line:
                 if last_line.startswith('-'):
                     tabs = len( self._PATTERN.match(last_line).group() )
                 else:
                     tabs = 0
                 if tabs < depth:
                     break
                 node = self._PATTERN.sub('', last_line.strip())
                 if tabs >= depth:
                     if parent is not None:
                         print "%s: %s" %(parent, node)
                         if parent in self.tree:
                             self.tree[parent].append(node)
                         else:
                             self.tree[parent] = [ node, ]
                     last_line = self._recurse_tree(node, tabs+1)
             return last_line
    

    Then use this like this:

    def main():
        inFile = open("data.txt")
        builder = TreeBuilder(inFile)
        pprint.pprint(builder.tree)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm creating import from XML function for categories. First of all, using XDocument, I
I am creating a large text file, the first line is a summary which
Summary : is there a way to get the unique lines from a file
I'm creating a class that can read from a dicom file. This is basically
I am creating a summary view of Microsoft InfoPath form(s) using a custom XSLT
Summary: I want to display a value (in a text box) stored in another
Summary: I'm trying to write a text string to a column of type varchar(max)
Summary of my question: Does NSURLConnection retain its delegate? Detailed question and scenario: I
I'm creating a summary view of products and prices, along with the ability to
Basically I am creating a summary table. The issue is that sometimes the data

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.