3 ms·
You can use dict's get() method to get back a None for missing keys instead of throwing a KeyError exception. That avoids the overhead of checking `if key in di
by cpeterso 8y ago
You can use dict's get() method to get back a None for missing keys instead of throwing a KeyError exception. That avoids the overhead of checking `if key in dict` or catching KeyError.
- wool_gather 8y agoAnother option, it's very easy to wrap a dict in a defaultdict: class optionaldict(defaultdict): """ A defaultdict that disregards KeyErrors and returns None for missing keys. """ def __init__(self, *original, **kwargs): super().__init__(lambda: None, *original, **kwargs)