我正在使用一个返回嵌套字典的包.
当其他所有内容都在对象语法中时,使用字典语法在类方法中访问此返回对象会感到很尴尬.
搜索带给我一堆/新推出的包,这似乎实现了我所追求的目标.我也看过建议使用的是namedtuples,但这些不容易支持嵌套属性,大多数解决方案依赖于在namedtuple中使用字典进行嵌套.
实现这一目标的更自然的方法是什么?
data = {'a': 'aval', 'b': {'b1':{'b2a':{'b3a':'b3aval','b3b':'b3bval'},'b2b':'b2bval'}} }
print(data['b']['b1']['b2a']['b3b']) # dictionary access
# print(data.b.b1.b2a.b3b) # desired access
import neobunch
data1 = neobunch.bunchify(data)
print(data1.b.b1.b2a.b3b)
解决方法:
以下课程可以让你做你想做的事:
class AttrDict(dict):
""" Dictionary subclass whose entries can be accessed by attributes
(as well as normally).
"""
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
@staticmethod
def from_nested_dict(data):
""" Construct nested AttrDicts from nested dictionaries. """
if not isinstance(data, dict):
return data
else:
return AttrDict({key: AttrDict.from_nested_dict(data[key])
for key in data})
data = {
"a": "aval",
"b": {
"b1": {
"b2b": "b2bval",
"b2a": {
"b3a": "b3aval",
"b3b": "b3bval"
}
}
}
}
data1 = AttrDict.from_nested_dict(data)
print(data1.b.b1.b2a.b3b) # -> b3bval