Python树结构之一行代码实现

用法

from collections import defaultdict
def tree(): return defaultdict(tree)
#or  tree = lambda: defaultdict(tree)

示例1

users = tree()
users['codingpy']['username'] = 'earlgrey'
users['python']['username'] = 'Guido van Rossum'

运行结果(print(json.dumps(users))

{"codingpy": {"username": "earlgrey"}, "python": {"username": "Guido van Rossum"}}

示例2

categories = tree()

categories['Programming Languages']['Python']
categories['Python']['Standard Library']['sys']
categories['Python']['Standard Library']['os']

运行结果(print(json.dumps(users))

{"Python": {"Standard Library": {"sys": {}, "os": {}}}, "Programming Languages": {"Python": {}}}

原文链接

你可能感兴趣的:(python)