Making Data Trees in Python
By: Keno Leon
Tags: Data Science, Python, Programming, Data Visualization, Coding

A tree you say ?

Most likely you are already using a tree or have used one, well at least a simple tree like this one:

We’ll get into the terminology in a minute, but the important thing here is the parent child relationship which might make more sense with a couple of examples:

Dad -> Son

Boss -> Employee

Favorite Food -> Chinese takeout

3 -> Silver Medal

Implementing this simple tree is fairly common in Python with dictionaries and lists :

⚠️ NOTE:The following examples are actually multiple trees ( technically a forest), in reality you are more likely to find this structure rather than a single tree ( at least at this level of tree complexity), if you remove say Jim and Carlos in the following example you would have a single tree. # Dictionary: Families = {'Peter':'Paul', 'Jim':'Tommy', 'Carlos':'Diego'} for Parent, Son in Families.items():

print(f"{Parent} is {Son}'s Dad")

OUTPUT: Peter is Paul's Dad

Jim is Tommy's Dad

Carlos is Diego's Dad





---------------------////------------------ #List: Prizes = ['Gold','Silver','Bronze','Nothing','Zilch'] for place, prize in enumerate(Prizes):

print(f"Place number {place+1} gets {prize}") OUTPUT: Place number 1 gets Gold

Place number 2 gets Silver

Place number 3 gets Bronze

Place number 4 gets Nothing

Place number 5 gets Zilch

But that looks nothing like a tree and these are simple linear relationships you might say. Well, yes but a tree starts to take shape and make sense once we add more children to the root node:

The key thing here is that these children have only one parent, if they had more this wouldn’t strictly be a tree ( it would be some sort of graph ), some examples:

Dad -> Son, Daughter

Boss -> Manager_1, Manager_2, Manager_3

Favorite Foods -> Chinese, Pizza, Tacos

1 -> Gold Medal,$10000,New Car,Sponsorship

Implementing these on Python should be straightforward since they are just expansions of the previous examples:

# Dictionary #(Same note as before, these are multiple trees, family trees in this example) : Families = {'Peter':['Paul','Patty'], 'Jim':['Tommy','Timmy','Tammy'], 'Carlos':['Diego']} for Parent, Children in Families.items():

print(f"{Parent} has {len(Children)} kid(s):" )

print(f"{', and '.join([str(Child) for Child in [*Children]])}") OUTPUT: Peter has 2 kid(s):

Paul, and Patty

Jim has 3 kid(s):

Tommy, and Timmy, and Tammy

Carlos has 1 kid(s):

Diego # Reduced/Alternative way of saying the same without thing formatting: for Parent, Children in Families.items():

print(str(Parent) + ' has ' + str(len(Children)) + ' kid(s):')

print(*Children) Note the use of the *Operator for unpacking the list.

---------------------\\ | // ------------------ # List: Prizes = [['Gold Medal','$10000','Sports Car','Brand Sponsorship'],

['Silver Medal','$5000','Budget Car'],

['Bronze Medal','$2500','Motorcycle'],

['Participation Trophy','Swag'],

['Swag']] for place, prizelist in enumerate(Prizes):

print(f"Place # {place+1} gets the following prize(s)")

print(f"{', and '.join([str(prize) for prize in [*prizelist]])}") OUTPUT:

Place # 1 gets the following prize(s)

Gold Medal, and $10000, and Sports Car, and Brand Sponsorship Place # 2 gets the following prize(s)

Silver Medal, and $5000, and Budget Car Place # 3 gets the following prize(s)

Bronze Medal, and $2500, and Motorcycle Place # 4 gets the following prize(s)

Participation Trophy, and Swag Place # 5 gets the following prize(s)

Swag

A more common tree then has a root element and multiple nodes which themselves have children of their own :

Some tree terminology ( Treeminology ?):

Part of what makes implementing a tree difficult (in general), is the hidden complexity a tree carries with it, here are some common terms you might encounter along with their graphical description: