sorin sorin - 1 year ago 101
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'
# >>> one a
# >>> b

Answer Source

dicts have a __missing__ hook for this:

class smart_dict(dict):
    def __missing__(self, key):
        return key
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download