gpt4 book ai didi

python - 嵌套字典的类对象属性访问

转载 作者:太空宇宙 更新时间:2023-11-03 14:11:00 30 4
gpt4 key购买 nike

我正在使用一个返回嵌套字典的包。当其他一切都在对象语法中时,使用字典语法在我的类方法中访问这个返回对象感觉很尴尬。搜索将我带到了 bunch/neobunch 包,这似乎实现了我所追求的。我还看到建议使用 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)

最佳答案

下面的类可以让你做你想做的事(适用于 Python 2 和 3):

class AttrDict(dict):
""" Dictionary subclass whose entries can be accessed by attributes (as well
as normally).

>>> obj = AttrDict()
>>> obj['test'] = 'hi'
>>> print obj.test
hi
>>> del obj.test
>>> obj.test = 'bye'
>>> print obj['test']
bye
>>> print len(obj)
1
>>> obj.clear()
>>> print len(obj)
0
"""
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self

@classmethod
def from_nested_dicts(cls, data):
""" Construct nested AttrDicts from nested dictionaries. """
if not isinstance(data, dict):
return data
else:
return cls({key: cls.from_nested_dicts(data[key]) for key in data})


if __name__ == '__main__':

data = {
"a": "aval",
"b": {
"b1": {
"b2b": "b2bval",
"b2a": {
"b3a": "b3aval",
"b3b": "b3bval"
}
}
}
}

attrdict = AttrDict.from_nested_dicts(data)
print(attrdict.b.b1.b2a.b3b) # -> b3bval

关于python - 嵌套字典的类对象属性访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38034377/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com