One-line tree in Python
#
Find similar titles
- 최초 작성자
- 최근 업데이트
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"}}