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
If you want to get None if a value is missing you can use the dict 's . get method to return a value ( None by default) if the key is missing. To just check if a key has a value in a dict , use the in or not in keywords.
Avoiding KeyError when accessing Dictionary Key We can avoid KeyError by using get() function to access the key value. If the key is missing, None is returned.
get() method returns a default value if the key is missing. However, if the key is not found when you use dict[key] , KeyError exception is raised.
A Python KeyError is raised when you try to access an item in a dictionary that does not exist. You can fix this error by modifying your program to select an item from a dictionary that does exist. Or you can handle this error by checking if a key exists first.
dict
s 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
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 have a default value!
If you want to have a go at the defaultdict
, try this:
dic = defaultdict() dic.__missing__ = lambda key: key dic['b'] # should set dic['b'] to 'b' and return 'b'
except... well: AttributeError: ^collections.defaultdict^object attribute '__missing__' is read-only
, so you will have to subclass:
from collections import defaultdict class KeyDict(defaultdict): def __missing__(self, key): return key d = KeyDict() print d['b'] #prints 'b' print d.keys() #prints []
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With