3 ms·
Well, for good or for bad, python does the same.
by enitihas 8y ago
Well, for good or for bad, python does the same.
- bpicolo 8y agoTo be fair, there's utility to avoid it: check first or do a .get(). That helps you be expressive about what you think should/should not exist
- p1necone 8y agoI can definitely see the use in that. In some situations a given key not being present would actually be exceptional.
- cpeterso 8y agoYou 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)