3 ms·
As pointed, you can use either a default dict or just simply, and [more pythonic](https://blogs.msdn.microsoft.com/pythonengineering/2016/06/29/idiomatic-python
by antoinealb 8y ago
As pointed, you can use either a default dict or just simply, and [more pythonic](https://blogs.msdn.microsoft.com/pythonengineering/2016/06/29/idiomatic-python-eafp-versus-lbyl/ https://blogs.msdn.microsoft.com/pythonengineering/2016/06/2...):
try:
bar[baz] += 1
except KeyError:
bar[baz] = 1
Also you can check if a key is in a dict simply by doing "if baz in bar" no need for "list(bar.keys())", which will be slow (temp object + linear scan) vs O(1) hashmap lookup.
- stfwn 8y agoThe error-catching method seemed too drastic to me before, but the article explains the LBYL vs. EAFP arugument quite well. Thanks! I should find a way to get more code reviews, I really enjoy learning these small nuggets of info.
- bb88 8y agoIt's also time saving since the hash lookup needs to be done at most 1, as well. GP has two lookups in the hash list.
- bocklund 8y agoAlternatively `bar[baz] = bar.get(baz, 0) + 1` One line and no error checking. But the OP was probably just illustrating a basic example where you might have some more intense logic