Skip to content

One-line tree in Python #

Find similar titles

6회 업데이트 됨.

Edit
  • 최초 작성자
    Sardor
  • 최근 업데이트
    JehongLee

Structured data

Category
Programming

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
print(json.dumps(companies))

And, we get result:

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