文章目录
- 背景
- 解决方案
- 基础版
- 升级版
背景
For example, instead of writing mydict[‘val’], I’d like to write mydict.val.
解决方案
基础版
I’ve always kept this around in a util file. You can use it as a mixin on your own classes too.
class dotdict(dict):
"""dot.notation access to dictionary attributes"""
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
mydict = {'val':'it works'}
nested_dict = {'val':'nested works too'}
mydict = dotdict(mydict)
print(mydict.val)
# 'it works'
mydict.nested = dotdict(nested_dict)
print(mydict.nested.val)
# 'nested works too'
这个时候嵌套字典行不行呢?也就是字典里的某一个值又是一个字典,不行!!!!!!
dict1={'val':'it works'}
yourdict={'high':dict1}
yourdict=dotdict(yourdict)
print(yourdict.high.val)
升级版
class DotDict(dict):
"""dot.notation access to dictionary attributes"""
def __getattr__(*args):
val = dict.get(*args)
return DotDict(val) if type(val) is dict else val
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
下面就成功了。
dict1={'val':'it works'}
yourdict={'high':dict1}
yourdict=DotDict(yourdict)
print(yourdict.high.val)
#it works