Search code examples
pythondictionarydata-structuresdictionary-missing

How to make a dictionary that returns key for keys missing from the dictionary instead of raising KeyError?


I want to create a python dictionary that returns me the key value for the keys are missing from the dictionary.

Usage example:

dic = smart_dict()
dic['a'] = 'one a'
print(dic['a'])
# >>> one a
print(dic['b'])
# >>> b

Solution

  • dicts have a __missing__ hook for this:

    class smart_dict(dict):
        def __missing__(self, key):
            return key
    

    Could simplify it as (since self is never used):

    class smart_dict(dict):
        @staticmethod
        def __missing__(key):
            return key