(1)、在python中使用字典可以很方便的查看属性,但是字典遍历的方法不是那么方便,因此python提供了快速遍历字典的方法。
dict1 = {'num1':1,'num2':2}
print(dict1['num1'])
#以上为普通的字典的遍历方法,这种遍历在应用的时候不是很方便,查找属性必须按照列表的方法进行查找
from easydict import EasyDict as edict
dict1 = {'num1':1,'num2':2}
dict2 = edict(dict1)
#dict2就可以按照方式dict2.num1进行访问
(2)以下用法:
from easydict import EasyDict as edict
#注意,这里的mn和cfg的值永远都是一样的!!!!!!!!!
#不管用哪个的值增加,另外一个都会变!!!!!!
mn = edict()
cfg = mn
mn.TRAIN = edict()
mn.TRAIN.LEARNING_RATE = 0.001
mn.TRAIN.MOMENTUM = 0.9
mn.TRAIN.GAMMA = 0.1
mn.TRAIN.STEPSIZE = 50000
mn.TRAIN.DISPLAY = 10
mn.IS_MULTISCALE = False
print(mn)
print(cfg)
print(cfg.TRAIN)
print(cfg.TRAIN.DISPLAY)
print(mn.TRAIN.MOMENTUM)
(3)改进型Easydict
class EasyDict(dict):
"""
Get attributes
>>> d = EasyDict({'foo':3})
>>> d['foo']
3
>>> d.foo
3
>>> d.bar
Traceback (most recent call last):
...
AttributeError: 'EasyDict' object has no attribute 'bar'
Works recursively
>>> d = EasyDict({'foo':3, 'bar':{'x':1, 'y':2}})
>>> isinstance(d.bar, dict)
True
>>> d.bar.x
1
Bullet-proof
>>> EasyDict({})
{}
>>> EasyDict(d={})
{}
>>> EasyDict(None)
{}
>>> d = {'a': 1}
>>> EasyDict(**d)
{'a': 1}
Set attributes
>>> d = EasyDict()
>>> d.foo = 3
>>> d.foo
3
>>> d.bar = {'prop': 'value'}
>>> d.bar.prop
'value'
>>> d
{'foo': 3, 'bar': {'prop': 'value'}}
>>> d.bar.prop = 'newer'
>>> d.bar.prop
'newer'
Values extraction
>>> d = EasyDict({'foo':0, 'bar':[{'x':1, 'y':2}, {'x':3, 'y':4}]})
>>> isinstance(d.bar, list)
True
>>> from operator import attrgetter
>>> map(attrgetter('x'), d.bar)
[1, 3]
>>> map(attrgetter('y'), d.bar)
[2, 4]
>>> d = EasyDict()
>>> d.keys()
[]
>>> d = EasyDict(foo=3, bar=dict(x=1, y=2))
>>> d.foo
3
>>> d.bar.x
1
Still like a dict though
>>> o = EasyDict({'clean':True})
>>> o.items()
[('clean', True)]
And like a class
>>> class Flower(EasyDict):
... power = 1
...
>>> f = Flower()
>>> f.power
1
>>> f = Flower({'height': 12})
>>> f.height
12
>>> f['power']
1
>>> sorted(f.keys())
['height', 'power']
"""
def __init__(self, d=None, **kwargs):
if d is None:
d = {}
if kwargs:
d.update(**kwargs)
for k, v in d.items():
setattr(self, k, v)
# Class attributes
for k in self.__class__.__dict__.keys():
if not (k.startswith('__') and k.endswith('__')):
setattr(self, k, getattr(self, k))
def __setattr__(self, name, value):
if isinstance(value, (list, tuple)):
def get_EasyDict_list(value):
return [EasyDict(x) if isinstance(x, dict) else x if not isinstance(x, (list, tuple)) else get_EasyDict_list(x) for x in value]
value = get_EasyDict_list(value)
else:
value = EasyDict(value) if isinstance(value, dict) else value
super(EasyDict, self).__setattr__(name, value)
self[name] = value
def __getattr__(self, name):
"""
如果 key 不存在返回 None
"""
try:
return super(EasyDict, self).__getattr__(name)
except AttributeError:
try:
return self[name]
except KeyError:
key = name or ""
if key.startswith('__') and key.endswith('__'):
raise AttributeError
return None