[英]How do I return nested dictionary keys as attributes from a class?
I have a function in my class: getNested() that is getting a bunch of data as a nested dictionary.我的 class: getNested() 中有一个 function:getNested() 将一堆数据作为嵌套字典。 What would be the best practice to convert this data into attributes I can then use when instancing the class?
在实例化 class 时,将这些数据转换为我可以使用的属性的最佳实践是什么? eg;
例如; running the line test.nestedDict.A in the example bellow would ideally return {'Aa': ['1', '2', '3',], 'Ab':'item'}.
在下面的示例中运行 test.nestedDict.A 行将理想地返回 {'Aa': ['1', '2', '3',], 'Ab':'item'}。
class MyClass( object ):
def __init__( self ):
self._nestedDict = None
self.getNested()
def getNested( self ):
self._nestedDict = {'A':{'Aa': ['1', '2', '3',], 'Ab':'item'}, 'B':{'Ba': ['4', '5', '6',], 'Bb':'item2'} }
@property
def nestedDict( self ):
return self._nestedDict
test = MyClass()
test.nestedDict
# Result: {'A': {'Aa': ['1', '2', '3'], 'Ab': 'item'},'B': {'Ba': ['4', '5', '6'], 'Bb': 'item2'}} #
test.nestedDict['A']
# Result: {'Aa': ['1', '2', '3'], 'Ab': 'item'} #
test.nestedDict.A
# Error: AttributeError: line 1: 'dict' object has no attribute 'A' #
One way to go to achieve what you want, would be by defining and using a helper class which inherits from dict
. go 实现您想要的一种方法是定义和使用从
dict
继承的助手 class 。 Then, within this class, setting the keys of the nested dictionary as attributes of the class.然后,在这个 class 中,将嵌套字典的键设置为 class 的属性。
This would look like:这看起来像:
class Nested(dict):
def __init__(self, dict_):
super(Nested, self).__init__()
for k, v in dict_.items():
if isinstance(v, dict):
v = Nested(v)
setattr(self, k, v)
self.update({k: v})
class MyClass:
def __init__(self):
self.set_nested()
def set_nested(self):
nested_dict = {'A': {'Aa': ['1', '2', '3'], 'Ab': 'item'},
'B': {'Ba': ['4', '5', '6'], 'Bb': 'item2'}}
self._nested_dict = Nested(nested_dict)
@property
def nested_dict( self ):
return self._nested_dict
With which you could then do:然后你可以这样做:
>>> test = MyClass()
>>> test.nested_dict
{'A': {'Aa': ['1', '2', '3'], 'Ab': 'item'}, 'B': {'Ba': ['4', '5', '6'], 'Bb': 'item2'}}
>>> test.nested_dict.A
{'Aa': ['1', '2', '3'], 'Ab': 'item'}
>>> test.nested_dict.A.Aa
['1', '2', '3']
>>> test.nested_dict.A.Ab
'item'
>>> test.nested_dict['A']
{'Aa': ['1', '2', '3'], 'Ab': 'item'}
Please, note that I allowed myself to change the name of the variables and methods to comply with PEP8 styling请注意,我允许自己更改变量和方法的名称以符合PEP8 样式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.