How to override a dict with Python?

Sometimes, we want to override a dict with Python.

In this article, we’ll look at how to override a dict with Python.

How to override a dict with Python?

To override a dict with Python, we can create a subclass of the MutableMapping class.

For instance, we weite

from collections.abc import MutableMapping


class TransformedDict(MutableMapping):
    def __init__(self, *args, **kwargs):
        self.store = dict()
        self.update(dict(*args, **kwargs))  

    def __getitem__(self, key):
        return self.store[self._keytransform(key)]

    def __setitem__(self, key, value):
        self.store[self._keytransform(key)] = value

    def __delitem__(self, key):
        del self.store[self._keytransform(key)]

    def __iter__(self):
        return iter(self.store)
    
    def __len__(self):
        return len(self.store)

    def _keytransform(self, key):
        return key

to create a TransformedDict class that is a subclass of the MutableMapping.

We use a dict as the value of the store instance variable.

And then we manipulate it in the instance methods to create our own behavior for a TransformedDict dict.

The __getitem__ method is used to get the item from the store dict.

__setitem__ sets the item in the store.

__delitem__ deletes an itemn with the key from the store dict.

__iter__ returns an iterator from the store dict.

__len__ returns the length of the dict.

And _keytransform transforms the dict key to our liking.

Conclusion

To override a dict with Python, we can create a subclass of the MutableMapping class.