File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python
2+ # encoding: utf-8
3+
4+ """
5+ @author: zhanghe
6+ @software: PyCharm
7+ @file: tree.py
8+ @time: 2017/5/22 下午6:57
9+ """
10+
11+
12+ import json
13+ from collections import defaultdict
14+
15+
16+ def tree ():
17+ """
18+ 定义一棵树
19+ python 字典的特性,赋值操作必须事先声明,所以这里使用 collections 很方便的为字典设置初始值
20+ :return:
21+ """
22+ return defaultdict (tree )
23+
24+
25+ if __name__ == '__main__' :
26+ users = tree ()
27+ users ['jack_1' ]['jack_2_1' ]['jack_3_1' ] = {}
28+ users ['jack_1' ]['jack_2_1' ]['jack_3_2' ] = {}
29+ users ['jack_1' ]['jack_2_2' ] = {}
30+ users ['jack_1' ]['jack_2_2' ]['jack_3_1' ] = {}
31+
32+ users ['lily_1' ]['lily_2_1' ]['lily_3_1' ] = {}
33+ users ['lily_1' ]['lily_2_2' ]['lily_3_2' ] = {}
34+ users ['lily_1' ]['lily_2_3' ]['lily_3_3' ] = {}
35+
36+ users ['emma_1' ]['emma_2_1' ] = {}
37+
38+ # 打印 users 原始结构
39+ print users
40+
41+ # 打印 users json 结构
42+ print (json .dumps (users , indent = 4 ))
43+
44+ # 第一层(users的key)
45+ print [i for i in users ]
46+
47+ # 第二层(users子节点的key)
48+ print [i for i in users ['jack_1' ]]
49+
50+ # 第三层(users孙节点的key)
51+ print [i for i in users ['jack_1' ]['jack_2_1' ]]
You can’t perform that action at this time.
0 commit comments