Antony
Antony

Reputation: 1

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. What would be the best practice to convert this data into attributes I can then use when instancing the class? eg; running the line test.nestedDict.A in the example bellow would ideally return {'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' # 

Upvotes: 0

Views: 543

Answers (1)

revliscano
revliscano

Reputation: 2272

One way to go to achieve what you want, would be by defining and using a helper class which inherits from dict. Then, within this class, setting the keys of the nested dictionary as attributes of the 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

Upvotes: 1

Related Questions