python 中easydict的简单使用

可以查看easydict官方网站:https://pypi.org/project/easydict/1.2/

easydict的作用:可以使得以属性的方式去访问字典的值!

  1. >>> from easydict import EasyDict as edict  
  2. >>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}})  
  3. >>> d.foo  
  4. 3  
  5. >>> d.bar.x  
  6. 1  
  7.   
  8. >>> d = edict(foo=3)  
  9. >>> d.foo

解析json目录时很有用

  1. >>> from easydict import EasyDict as edict  
  2. >>> from simplejson import loads  
  3. >>> j = """{ 
  4. "Buffer": 12, 
  5. "List1": [ 
  6.     {"type" : "point", "coordinates" : [100.1,54.9] }, 
  7.     {"type" : "point", "coordinates" : [109.4,65.1] }, 
  8.     {"type" : "point", "coordinates" : [115.2,80.2] }, 
  9.     {"type" : "point", "coordinates" : [150.9,97.8] } 
  10. }"""  
  11. >>> d = edict(loads(j))  
  12. >>> d.Buffer  
  13. 12  
  14. >>> d.List1[0].coordinates[1] 

也可以这样用

  1. >>> d = EasyDict()  
  2. >>> d.foo = 3  
  3. >>> d.foo  
  4. 3  
  1. >>> d = EasyDict(log=False)  
  2. >>> d.debug = True  
  3. >>> d.items()  
  4. [('debug', True), ('log', False)] 
  1. >>> class Flower(EasyDict):  
  2. ...     power = 1  
  3. ...  
  4. >>> f = Flower({'height': 12})  
  5. >>> f.power  
  6. 1  
  7. >>> f['power']  

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': {}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值