Customize Dictionary using UserDict

Posted by Afsal on 16-Dec-2022

Hi Pythonistas!

Today we will learn how to customize the dictionary using UserDict from the collections module. Let us make a dictionary that accepts an only string as its key.

Code

from collections import UserDict

class StringKeyDict(UserDict):
    def __setitem__(self, key, value):
        if type(key) != str or not key.isalpha():
            raise Exception('Key must be alphabet')
    super().__setitem__(key, value)

a = StringKeyDict()
a["a"] = "test"
a["b"] = 2
print(a)
a["ab2"] = "test"

Output

{'a': 'test', 'b': 2}
Traceback (most recent call last):
  File "experiment.py", line 21, in <module>
a["ab2"] = "test"
~^^^^^^^
  File "experiment.py", line 11, in __setitem__
raise Exception('Key must be alphabet')
Exception: Key must be alphabet

Here in this example StringKeyDict’s __setitem__ is overridden so when we set an item this check whether the key is alphabets only ie a-zA-Z. Everything except this works like normal dict.

When we tried to set ab2 it has a digit so this will raise and Exception.

By customizing the proper magic method we can make the desired behavior. Hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in