嵌套字典的类对象属性访问 [英] Object-like attribute access for nested dictionary
问题描述
我正在使用一个返回嵌套字典的包. 当其他所有内容都是对象语法时,使用字典语法访问我的类方法中的此返回对象会感到很尴尬. 搜索使我进入了大包/新捆绑包,这似乎实现了我的追求.我还看到了namedtuples的建议,但是它们不容易支持嵌套属性,大多数解决方案都依赖于使用namedtuple中的字典进行嵌套.
I'm utilising a package which returns a nested dictionary. It feels awkward to access this return object in my class methods with the dictionary syntax, when everything else is in object syntax. Searching has brought me to the bunch / neobunch packages, which seems to achieve what I'm after. I've also seen namedtuples suggested but these do not easily support nested attributes and most solutions rely on using dictionaries within the namedtuple for nesting.
实现这一目标的更自然的方法是什么?
What would be a more natural way of achieving this?
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)
推荐答案
下面的类可以让您做自己想做的事情:
The following class would let you do what you want:
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
这篇关于嵌套字典的类对象属性访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!