sorin sorin - 2 months ago 18
Python Question

How to make a python 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

Answer

dicts have a __missing__ hook for this:

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