可以查看easydict官方网站:https://pypi.org/project/easydict/1.2/
easydict的作用:可以使得以属性的方式去访问字典的值!
- >>> from easydict import EasyDict as edict
- >>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}})
- >>> d.foo
- 3
- >>> d.bar.x
- 1
- >>> d = edict(foo=3)
- >>> d.foo
解析json目录时很有用
- >>> from easydict import EasyDict as edict
- >>> from simplejson import loads
- >>> j = """{
- "Buffer": 12,
- "List1": [
- {"type" : "point", "coordinates" : [100.1,54.9] },
- {"type" : "point", "coordinates" : [109.4,65.1] },
- {"type" : "point", "coordinates" : [115.2,80.2] },
- {"type" : "point", "coordinates" : [150.9,97.8] }
- ]
- }"""
- >>> d = edict(loads(j))
- >>> d.Buffer
- 12
- >>> d.List1[0].coordinates[1]
也可以这样用
- >>> d = EasyDict()
- >>> d.foo = 3
- >>> d.foo
- 3
- >>> d = EasyDict(log=False)
- >>> d.debug = True
- >>> d.items()
- [('debug', True), ('log', False)]
- >>> class Flower(EasyDict):
- ... power = 1
- ...
- >>> f = Flower({'height': 12})
- >>> f.power
- 1
- >>> f['power']
- 1
Easydict的其他用法:
设置属性:
from easydict import EasyDict as edict
d = edict() # 这个是输出{}
d.foo = 3 # 我们可以直接赋值语句对字典元素进行创建
d.bar = {'prob':'value'} # 另外我们也可以创建字典中的字典
d.bar.prob = 'newer' # 另外我们也可以很方便的修改字典中元素的值
print(d)
输出:
{'foo': 3, 'bar': {'prob': 'newer'}}
在深度学习中往往利用easydict建立一个全局的变量:
from easydict import EasyDict as edict
config = edict()
config.TRAIN = edict() # 创建一个字典,key是Train,值是{}
config.Test = edict()
# config.TRAIN = {} # 这个和上面的那句话是等价的,相当于创建一个字典的key
config.TRAIN.batch_size = 25 # 然后在里面写值,表示Train里面的value也是一个字典
config.TRAIN.early_stopping_num = 10
config.TRAIN.lr = 0.0001
print(config)
输出:
{'TRAIN': {'batch_size': 25, 'early_stopping_num': 10, 'lr': 0.0001}, 'Test': {}}