Best way to handle a keyerror in a dict
collections.defaultdict could help to build a pythonic code:
count = collections.defaultdict(int) # => default value is 0
...
count[event] += 1 # will end to 1 on first hit and will increment later
The most appropriate data structure for what you want to do is collections.Counter
, where missing keys have an implicit value of 0
:
from collections import Counter
events = Counter()
for e in "foo", "bar", "foo", "tar":
events[e] += 1
You can use dict.get
if you want to use dict
mydict[key] = mydict.get(key, 0) + 1
Or you can handle KeyError
try:
mydict[key] += 1
except KeyError:
mydict[key] = 1
Or you can use defaultdict
from collections import defaultdict
mydict = defaultdict(int)
mydict[key] += 1