Skip to content

One-line tree in Python #
Find similar titles

Structured data


Python has built-in defaultdict, so everyone can easily define a tree data structure:

def tree(): return defaultdict(tree)

Above implementation shows that tree is a dict whose default values are trees.

Some Python version may have to import defaultdict like following:

from collections import defaultdict

Example #

We can make JSON-like nested dictionaries without making sub-dictionaries as it magically comes into existence if we reference them:

companies = tree()
companies['company']['name'] = 'insilicogen'
companies['company']['dept'] = 'data science center'

Let's print this as json with:

import json

And, we get result:

{"company": {"dept": "data science center", "name": "insilicogen"}}