Search code examples
pythondictionaryextend

What is the proper way to extend the Dict class?


I want to implement two different dictionaries with a predefined set of valid keys. Also, one dictionary contains the other.

class Otherdict (dict):

    _keys = ['A','B']

    def __init__(self):
        for key in self._keys:
            self[key] = None

    def populateDict(self):
        self['B'] = 10
        self['A'] = 12

class MyDict(dict):

    _keys = ['R','ED']

    def __init__(self):
        for key in self._keys:
            self[key] = None

    def __getitem__(self, key):
        if key not in self._keys:
            raise Exception("'" + key + "'" + " is not a valid key")
        dict.__getitem__(self,key)

    def __setitem__(self, key, value):
        if key not in self._keys:
            raise Exception("'" + key + "'" + " is not a valid key")
        dict.__setitem__(self,key,value)

    def populateDict(self):
        d = Otherdict()
        d.populateDict()
        self['R'] = 3
        self['ED'] = d


a = MyDict()
a.populateDict()
print a['ED'].__class__    #prints <type 'NoneType'>

The problem is that for some reason I cannot access the dictionary located under the 'ED' key. What am I doing wrong here?

I've also noticed that if I remove the __getitem__() method, the code works properly


Solution

  • __getitem__ must return a value:

    def __getitem__(self, key):
        if key not in self._keys:
            raise Exception("'" + key + "'" + " is not a valid key")
        return dict.__getitem__(self,key)
    

    If there is no explicit return statement, Python functions return None by default.