Nikolay Fominyh
Nikolay Fominyh

Reputation: 9236

Properties over nested dictionary

We have properties, that work over nested dictionaries:

class A(object):
    _x = {}

    @property
    def z(self):
       return self._x.get('_y', {}).get('_z')

    @z.setter
    def z(self, value):
        if not self._x.get('_y'):
           self._x['_y'] = {}
        self._x['_y']['_z'] = value

How to create property y to rid off from check:

if not self._x.get('_y'):
   self._x['_y'] = {}

z setter must finally look like:

@z.setter
def z(self, value):
   self.x.y['_z'] = value

Upvotes: 0

Views: 126

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

use setdefault:

@z.setter
def z(self, value):        
    self._x.setdefault('_y',{})['_z'] = value

if _y exists in self._x, it retrieves it, else it creates a new dictionary.

Upvotes: 2

Related Questions