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 回答1: dict s have a __missing__ hook for this: class smart_dict(dict): def __missing__(self, key): return key 回答2: Why don't you just use dic.get('b', 'b') Sure, you can subclass dict as others point out, but I find it handy to remind myself every once in a while that get can