简体   繁体   English

如何从 class 中返回嵌套字典键作为属性?

[英]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.

相关问题 如何从 Python 中的嵌套字典中删除某些键? - How do I remove certain keys from a nested dictionary in Python? 如果一个字典中的键与另一个字典中的键匹配,如何返回新字典? - How do I return a new dictionary if the keys in one dictionary, match the keys in another dictionary? 从嵌套字典 Python 返回键 - Return keys from nested dictionary Python 如何从嵌套字典中获取键? - How can I get the keys from a nested dictionary? 如何使用更新的键和值从旧的嵌套字典创建新的嵌套字典? - How can I create a new nested dictionary from an old nested dictionary with updated keys and value? 如何从嵌套字典创建平面字典,其字符串是引用字典的子集? - How can I create a flat dictionary from a nested dictionary whose keys are a subset of a reference dictionary? 假设我有一本字典。 如何剥离所有钥匙? 编辑:这是一个嵌套的字典 - Suppose I have a dictionary. How do I strip out all the keys? Edit: This is a nested dictionary 如何将 output class 作为嵌套字典,如果其他属性为 != None 则计算属性 - How to output class as nested dictionary with attributes calculated if other attributes are != None 如何将键从嵌套字典输出到csv - How to output keys from nested dictionary to csv 如何从嵌套字典的键构建路径? - How to build path from keys of nested dictionary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM